Sum of Greatest Common Divisor of all numbers till n with n
问题 There are n numbers from 1 to n. I need to find the ∑gcd(i,n) where i=1 to i=n for n of the range 10^7. I used euclid's algorithm for gcd but it gave TLE. Is there any efficient method for finding the above sum? #include<bits/stdc++.h> using namespace std; typedef long long int ll; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int main() { ll n,sum=0; scanf("%lld",&n); for(int i=1;i<=n;i++) { sum+=gcd(i,n); } printf("%lld\n",sum); return 0; } 回答1: You can do it via bulk GCD