數論-歐拉函數

來源:互聯網
上載者:User

標籤:include   scan   bre   ems   mes   code   資料   names   max   

一:直接求歐拉函數

#include<cmath>#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;int main(void){    int n;    while(~scanf("%d",&n))    {        int ans = n;        int m = sqrt(n+0.5);        for(int i = 2; i <= m; i++)        {            if(n==1)                break;            if(n%i==0)            {                ans = ans/i*(i-1);                while(n%i==0)                     n = n / i ;            }        }        if(n!=1)            ans = ans/n*(n-1);        printf("%d\n",ans);    }    return 0;}

二:打表

#include<cmath>#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;const int maxn = 100;int euler[maxn];void Init(){     euler[1]=1;     for(int i = 2; i <= maxn; i++)       euler[i]=i;     for(int i = 2; i <= maxn; i++)        if(euler[i]==i)           for(int j = i; j <= maxn; j+=i)              euler[j]=euler[j]/i*(i-1);//先進行除法是為了防止中間資料的溢出}int main(void){    Init();    for(int i = 1; i <= maxn; i++)    {        printf("%d %d\n",i,euler[i]);    }    return 0;}

三:歐拉函數的線性篩法

原理:1若p是質數,則φ(p)=p-1;

   2:若i%p==0,則φ(i*p)=p*φ(i);

   3:若i%p!=0,則φ(i*p)=φ(i)*(p-1)

#include<cmath>#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;const int maxn = 100;int book[maxn];int prime[maxn];int phi[maxn];int num;void Init() {    memset(book, 0, sizeof (book));    phi[1] = 1;    book[0] = 1;     book[1] = 1;    for (int i = 2; i <= maxn; i++)     {        if (book[i]==0)         {            prime[num++] = i;            phi[i] = i - 1;        }        for (int j = 0; j < num; j++)         {            int p = prime[j];            if (i * p > maxn)                 break;            book[i * p] = 1;            phi[i * p] = (i % p == 0 ? phi[i] * p : phi[i] * (p - 1));            if (i % p == 0)                 break;        }    }}int main(void){    Init();    for(int i = 1; i < maxn; i++)        printf("%d %d\n",i,phi[i]);    return 0;}

 

數論-歐拉函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.