Series with largest GCD and sum equals to n | Java program to find the series with largest GCD and sum equals to n ; function to generate and print the sequence ; stores the maximum gcd that can be possible of sequence . ; if maximum gcd comes out to be zero then not possible ; the smallest gcd possible is 1 ; traverse the array to find out the max gcd possible ; checks if the number is divisible or not ; checks if x is smaller then the max gcd possible and x is greater then the resultant gcd till now , then r = x ; checks if n / x is smaller than the max gcd possible and n / x is greater then the resultant gcd till now , then r = x ; traverses and prints d , 2d , 3d , ... , ( k - 1 ) ; computes the last element of the sequence n - s . ; prints the last element ; driver program to test the above function
import java . io . * ; class GFG { static void print_sequence ( int n , int k ) { int b = n / ( k * ( k + 1 ) / 2 ) ; if ( b == 0 ) { System . out . println ( " - 1" ) ; } else { int r = 1 ; for ( int x = 1 ; x * x <= n ; x ++ ) { if ( n % x != 0 ) continue ; if ( x <= b && x > r ) r = x ; if ( n / x <= b && n / x > r ) r = n / x ; } for ( int i = 1 ; i < k ; i ++ ) System . out . print ( r * i + " ▁ " ) ; int res = n - ( r * ( k * ( k - 1 ) / 2 ) ) ; System . out . println ( res ) ; } } public static void main ( String [ ] args ) { int n = 24 ; int k = 4 ; print_sequence ( n , k ) ; n = 24 ; k = 5 ; print_sequence ( n , k ) ; n = 6 ; k = 4 ; print_sequence ( n , k ) ; } }