Function to return the maximum N such that the sum of the squares of first N natural numbers is not more than X
function findMaxN ( $ X ) { $ low = 1 ; $ high = 100000 ; $ N = 0 ; while ( $ low <= $ high ) { $ mid = ( int ) ( $ high + $ low ) / 2 ; if ( squareSum ( $ mid ) <= $ X ) { $ N = $ mid ; $ low = $ mid + 1 ; } else $ high = $ mid - 1 ; } return $ N ; }