Find maximum N such that the sum of square of first N natural numbers is not more than X | Java implementation of the approach ; Function to return the sum of the squares of first N natural numbers ; Function to return the maximum N such that the sum of the squares of first N natural numbers is not more than X ; Iterate through the maxvalue of N and find the ith position ; If the condition fails then return the i - 1 i . e sum of squares till i - 1 ; Driver code
class GFG { static long squareSum ( long N ) { long sum = ( long ) ( N * ( N + 1 ) * ( 2 * N + 1 ) ) / 6 ; return sum ; } static long findMaxN ( long X ) { long N = ( long ) Math . sqrt ( X ) ; for ( long i = 1 ; i <= N ; i ++ ) { if ( squareSum ( i ) > X ) return i - 1 ; } return - 1 ; } public static void main ( String [ ] args ) { long X = 25 ; System . out . println ( findMaxN ( X ) ) ; } }