Last element remaining after repeated removal of Array elements at perfect square indices | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findRemainingIndex ( int N ) { int ans = N ; while ( N > 1 ) { int discard = int ( sqrt ( N ) ) ; if ( discard * discard == N ) { ans -- ; } N -= discard ; } return ans ; } void findRemainingElement ( int arr [ ] , int N ) { int remainingIndex = findRemainingIndex ( N ) ; cout << arr [ remainingIndex - 1 ] ; } signed main ( ) { int arr [ ] = { 2 , 3 , 4 , 4 , 2 , 4 , -3 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findRemainingElement ( arr , N ) ; return 0 ; }