Last element remaining after repeated removal of Array elements at perfect square indices | Python 3 program for the above approach ; Function to find last remaining index after repeated removal of perfect square indices ; Initialize the ans variable as N ; Iterate a while loop and discard the possible values ; Total discarded values ; Check if this forms a perfect square ; Decrease answer by 1 ; Subtract the value from the current value of N ; Return the value remained ; Function to find last remaining element after repeated removal of array element at perfect square indices ; Find the remaining index ; Print the element at that index as the result ; Driver Code ; Given input
from math import sqrt NEW_LINE def findRemainingIndex ( N ) : NEW_LINE INDENT ans = N NEW_LINE while ( N > 1 ) : NEW_LINE INDENT discard = int ( sqrt ( N ) ) NEW_LINE if ( discard * discard == N ) : NEW_LINE INDENT ans -= 1 NEW_LINE DEDENT N -= discard NEW_LINE DEDENT return ans NEW_LINE DEDENT def findRemainingElement ( arr , N ) : NEW_LINE INDENT remainingIndex = findRemainingIndex ( N ) NEW_LINE print ( arr [ remainingIndex - 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 4 , 2 , 4 , - 3 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE findRemainingElement ( arr , N ) NEW_LINE DEDENT