FZU 1969 GCD Extreme,UESTC 1723 吴神的大脑: _数论好题(求1-n中所有数的最大公约数之和)

Problem Description

Given the value of N, you will have to find the value of G. The meaning of G is given in the following code

G=0; 
for(i=1;i 
    
    for(j=i+1;j<=N;j++) 

        G+=gcd(i,j); 

/*Here gcd() is a function that finds the greatest common divisor of the two input numbers*/

Input

The input file contains at most 20000 lines of inputs. Each line contains an integer N (1

Output

For each line of input produce one line of output. This line contains the value of G for the corresponding N. The value of G will fit in a 64-bit signed integer.

Sample Input

101002000000

Sample Output

6713015143295493160

Source

Contest for 2010 lecture II


//一道很不错的数论题,在UESTC OJ和SPOJ上都有,都分别测试了下! 

//针对题目开始给出的公式可以转换为是给出一个n,求

for(m=1;m<=n;m++)

每一个m值与它(不包括自身)之前所有数的公约数之和。

显然直接对每一个m从1-(m-1)循环每次求出最大公约数的时间复杂度是O(n^2)肯定TLE.。  由于m从1循环到n,而求m与它之前的数最大公约数又是从1循环到(m-1),其中有很多公约数的重复的计算,那么可以换个角度考虑,考虑一个数d它可以做哪些数的最大公约数,则枚举公约数d (1~n),d一共出现了sigma(phi(i))-1  (1<=i<=[N/d])次 ,而

sigma(phi(i))通过预处理可以O(1)得到。所以时间复杂度从O(n^2)降到了O(n),UESTC  OJ上面此题说明了case最多只有100组,那么O(n)的复杂度便可以过了,500+ms过了。 而SPOJ 和FZU 上此题都说明了case 有20000组,那么效率如果是O(case*n)的话肯定超时。 则要寻求更高效的算法,想了很久都没有办法,看了SPOJ提供的解题报告暴强,模拟素数筛选的过程,d可以作为后面某些数的最大公约数,则将d*phi[n/d]与n/d*phi[d]全都更新保存到相应的数组里面,用O(sqrt(n))的效率预处理出1000000以内所有数的G值,最后O(1)查询便可。  UESTC OJ上面96ms AC. 而FZU 上20000个case 也只要140+ms便AC了。

O(n)算法: //UESTC:1723
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define maxn 1000005
#define LL long long

int phi[maxn];
LL sumphi[maxn];

void Init()
{
	int i,j;
	memset(sumphi,0,sizeof(sumphi));
	for(i=1;i


//O(sqrt(n))算法:(FZU 1969)
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define maxn 1000005
#define LL __int64

int phi[maxn];
LL ans[maxn]; //ans[x]=sum(ans[i]*j); (i*j=x)
void Init()
{
	int i,j,k;
	for(i=2;i



你可能感兴趣的:(数学)