Series with largest GCD and sum equals to n | CPP 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 ) d , ; computes the last element of the sequence n - s . ; prints the last element ; driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print_sequence ( int n , int k ) { int b = n / ( k * ( k + 1 ) / 2 ) ; if ( b == 0 ) { cout << -1 << endl ; } 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 ++ ) cout << r * i << " ▁ " ; int res = n - ( r * ( k * ( k - 1 ) / 2 ) ) ; cout << res << endl ; } } int main ( ) { 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 ) ; }