top of page
Click here to go to the home page of AskTheCode.

An Interesting Sequence CodeChef Soution - AskTheCode

Team ATC

Updated: Jun 14, 2021

CodeChef May Long Challenge 2021 Solution | Codechef solution | AskTheCode

 

Problem:

Zanka finds fun in everyday simple things. One fine day he got interested in a very trivial sequence. Given a natural number k, he considers the sequence Ai=k+i^2

so that the terms are

k+1,k+4,k+9,k+16,…


Now to make things more interesting, he considers the gcd of consecutive terms in the sequence, then takes the sum of the first 2k values. More formally, he wants to compute

Denote this sum by S. Zanka wants you to print the number S for each k.

 

Input:

  • The first line contains an integer T, the number of test cases. Descriptions of test cases follow.

  • The only line of each test case contains a single integer k.

 

Output:

For each test case, output a single line containing the sum S for the given k.

 

Constraints:

  • 1 <= T <= 10^6

  • 1 <= k <= 10^6

 

Sample Input:

1
1
 

Sample Output:

6
 

Explanation:

The first 2k+1 terms of the sequence A are 2,5,10.

So the answer is gcd(2,5)+gcd(5,10)=1+5=6.

 

Code:

#include <iostream>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int N=4e6+5;
    int phi[N],answer[N];
    for(int i=0;i<N;i++){
        phi[i]=i;
        answer[i]=0;
    }
    for(int p=2;p<N;p++){
        if(phi[p]==p){
            phi[p]=p-1;
            for(int i=2*p;i<N;i+=p)
                phi[i]=(phi[i]/p)*(p-1);
        }
    }
    for(int i=1;i<N;i++){
        answer[i]+=i-1;
        for(int j=2*i;j<N;j+=i){
            answer[j]+=i*((1+phi[j/i])/2);
        }
    }
    int t;
    cin>>t;
    while(t--){
        int k;
        cin >> k;
        cout << answer[4*k+1]<<"\n";
    }
	return 0;
}

Recent Posts

See All

Comments


bottom of page