Sum of largest divisor of numbers upto N not divisible by given prime number P | Java program for the above approach ; Function to find the sum of largest divisors of numbers in range 1 to N not divisible by prime number P ; Total sum upto N ; If no multiple of P exist up to N ; If only P itself is in the range from 1 to N ; Sum of those that are divisible by P ; Recursively function call to find the sum for N / P ; Driver Code ; Given N and P ; Function call
class GFG { static int func ( int N , int P ) { int sumUptoN = ( N * ( N + 1 ) / 2 ) ; int sumOfMultiplesOfP ; if ( N < P ) { return sumUptoN ; } else if ( ( N / P ) == 1 ) { return sumUptoN - P + 1 ; } sumOfMultiplesOfP = ( ( N / P ) * ( 2 * P + ( N / P - 1 ) * P ) ) / 2 ; return ( sumUptoN + func ( N / P , P ) - sumOfMultiplesOfP ) ; } public static void main ( String [ ] args ) { int N = 10 , P = 5 ; System . out . println ( func ( N , P ) ) ; } }