zoukankan      html  css  js  c++  java
  • poj 2478 Farey Sequence(欧拉函数是基于寻求筛法素数)

    http://poj.org/problem?id=2478


    求欧拉函数的模板。

    初涉欧拉函数,先学一学它主要的性质。

    1.欧拉函数是求小于n且和n互质(包含1)的正整数的个数。

    记为φ(n)。

    2.欧拉定理:若a与n互质。那么有a^φ(n) ≡ 1(mod n),经经常使用于求幂的模。

    3.若p是一个质数,那么φ(p) = p-1。注意φ(1) = 1。

    4.欧拉函数是积性函数:

    若m与n互质,那么φ(nm) = φ(n) * φ(m)。

    若n = p^k且p为质数,那么φ(n) = p^k - p^(k-1) = p^(k-1) * (p-1)。

    5.当n为奇数时,有φ(2*n) = φ(n)。

    6.基于素数筛的求欧拉函数的重要根据:

    设a是n的质因数,若(N%a == 0 && (N/a)%a == 0) 则 φ(N) = φ(N/a)*a; 若(N%a == 0 && (N/a)%a != 0) 则φ(N) = φ(N/a)*(a-1)。


    该题就是基于性质六,在线性时间内求欧拉函数。

    #include <stdio.h>
    #include <iostream>
    #include <algorithm>
    #include <set>
    #include <map>
    #include <vector>
    #include <math.h>
    #include <string.h>
    #include <queue>
    #include <string>
    #include <stdlib.h>
    #define LL long long
    #define _LL __int64
    #define eps 1e-8
    #define PI acos(-1.0)
    
    using namespace std;
    const int maxn = 1000010;
    const int INF = 0x3f3f3f3f;
    
    int n;
    LL num[maxn];
    
    LL phi[maxn]; //相应φ(i)
    int flag[maxn]; //flag[i] = 0说明i是素数。否则不是素数
    int prime[maxn];//存素数
    
    void get_phi()
    {
    	int i,j,k;
    	memset(flag,0,sizeof(flag));
    	phi[1] = 1;
    	k = 0;
    
    	for(i = 2; i <= maxn; i++)
    	{
    		if(!flag[i]) //i是素数
    		{
    			phi[i] = i-1;
    			prime[++k] = i;
    		}
    		for(j = 1; j <= k && prime[j]*i <= maxn; j++)
    		{
    			flag[i*prime[j]] = 1;
    			if(i % prime[j] == 0)
    				phi[i*prime[j]] = phi[i] * prime[j];
    			else phi[i*prime[j]] = phi[i] * (prime[j]-1);
    		}
    	}
    }
    
    int main()
    {
    	get_phi();
    	num[1] = 0;
    	for(int i = 2; i <= maxn; i++)
    		num[i] = num[i-1] + phi[i];
    
    	while(~scanf("%d",&n)&&n)
    		printf("%lld
    ",num[n]);
    
    	return 0;
    }
    


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    Visual Studio 2015编译64位MySQL Connector/C++
    html.parser无法完全解析网页之BUG的修正
    Boost-Visual studio 2015环境配置
    Struts2--拦截器和常用标签库
    Struts2---OGNL表达式和值栈的运用
    Struts2---对Servlet的API的访问,结果页面的配置,数据的封装
    Struts2---入门
    spring mvc 文件上传
    ElasticSearch 基本操作
    SpringBoot 项目打包后获取不到resource下资源的解决
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4613257.html
Copyright © 2011-2022 走看看