hdu2582 f(n)(规律:质因子分解)

题意:
This time I need you to calculate the f(n) . (3<=n<=1000000)
f ( n ) = G c d ( 3 ) + G c d ( 4 ) + + G c d ( i ) + + G c d ( n ) . f(n)= Gcd(3)+Gcd(4)+…+Gcd(i)+…+Gcd(n).
G c d ( n ) = g c d ( C [ n ] [ 1 ] , C [ n ] [ 2 ] , , C [ n ] [ n 1 ] ) Gcd(n)=gcd(C[n][1],C[n][2],……,C[n][n-1])
C [ n ] [ k ] C[n][k] means the number of way to choose k things from n some things.
g c d ( a , b ) gcd(a,b) means the greatest common divisor of a a and b b .
思路:
一开始对答案打表,发现毫无规律,原来是打表的打开方式不对~~
堆GCD打表
如下
3
3
4
3 2
5
3 2 5
6
3 2 5 1
7
3 2 5 1 7
8
3 2 5 1 8 2

发现,如果对于 G C D ( n ) GCD(n) ,如果 n n ,有一个质因子,那么 G C D n GCD(n) = 这个质因子,否则 G C D n = 1 GCD(n) = 1 。预处理输出即可。试除法预处理的时间复杂度为 n n n\sqrt{n} .

A C   C o d e : AC\ Code:

#include<iostream>
#include<cstring>
#include<queue>
#include<map>
#include<cmath>
#include<set>
#include<stack>
#include<cstdio>
#include<sstream>
#include<vector>
#include<bitset>
#include<algorithm>

using namespace std;
#define read(x) scanf("%d",&x)
#define Read(x,y) scanf("%d%d",&x,&y)
#define gc(x)  scanf(" %c",&x);
#define mmt(x,y)  memset(x,y,sizeof x)
#define write(x) printf("%d\n",x)
#define pii pair<int,int>
#define INF 0x3f3f3f3f
#define ll long long
const int N = 100000 + 100;
const int M = 3e6 + 1005;
typedef long long LL;
int gcd(int a,int b){
    if(b) return gcd(b,a%b);
    else return a;
}
ll f[M];
int prim[M];
int tot = 0;
void init(){
    int x;
    for(int i = 3;i <= 1000000;++i){
        x = i;
        tot = 0;
        for(int j = 2;j * j<=x;++j){
            if(!(x%j)){
                prim[++tot] = j;
                while(!(x%j)) x /= j;
            }
        }
        if(x > 1) prim[++tot] = x;
        if(tot > 1) f[i] = 1;
        else f[i] = prim[1];
        f[i] += f[i-1];//递推预处理
    }
}
int main(){
    int n;
    init();
    while(scanf("%d",&n)==1){
        printf("%lld\n",f[n]);
    }
}
发布了632 篇原创文章 · 获赞 27 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43408238/article/details/103614436