题目链接:https://ac.2333.moe/Problem/view.xhtml?id=1613
[1613] GCD
时间限制: 2000 ms 内存限制: 65535 K
问题描述
Given an integer n(1 <= n <= 400000), you need to calculator the sum of all gcd(i, j) for 1 <= i < j <= n.
输入
Each test case contains an integer n.
The last line contains 0, you need not to process it.
输出
For each test case, print the sum of of all gcd(i, j) for 1 <= i < j <= n.
样例输入
3
12452
样例输出
3
424642359
题目大意:题目的意思很好理解,就是求 gcd(1,2),gcd(1,3),gcd(1,n),gcd(2,3),,,,gcd(n-1,n)这些的和
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
__int64 num[400010];
int main()
{
int n;
__int64 ans = 0;
while (~scanf("%d",&n))
{
ans = 0;
memset(num,0,sizeof(num));
if (n == 0)
{
break;
}
for (int i = n ; i >= 1 ; --i )
{
__int64 temp = n / i; //计算从i~n中能被i整除的数字有几个
if(temp <= 1) //如果小于等于1 就说明没有
{
num[i] = 0;
}
else
{
num[i] = temp * (temp -1 ) / 2; //这个是i~n,i~n-1,i~n-2,,,这些的和
}
for (int j = 2 * i ; j <= n ; j += i) //如果能被i 整除,并且又能被i 的倍数整除,那么 公约数不会是i 所以需要减去能被i倍数整除的个数
{
num[i] -= num[j];
}
ans += num[i] * i; //i为最大公约数的个数乘于i ,,就是i 这个数总共的和
}
printf("%I64d\n",ans); //最后输出答案
}
return 0;
}