Thursday, June 16, 2016

EulerPhi source code

Theorem 1: If m and n are coprime, then ϕ(m×n)=ϕ(m)×ϕ(n)


Theorem 2: In an arithmetic progression with difference of m, if we take n terms and find their modulo by n, and if n and m are coprimes, then we will get the numbers from 0 to n1 in some order.

Theorem 3: If a number x is coprime to y, then (x%y) will also be coprime to y.

#include<bits/stdc++.h>

using namespace std;

bool status[11000010];

vector<int>prime;

void sieve()
{
    int n=10000010;
    int sq=sqrt(n);

    for(int i=4; i<=n; i=i+2) status[i]=true;

    for(int i=3; i<=sq; i=i+2)
    {
        if(status[i]==false)
        {

            for(int j=i*i; j<=n; j=j+i) status[j]=true;
        }
    }
    status[1]=1;
    status[0]=1;

    prime.push_back(2);

    for(int i=3; i<=n; i=i+2)
    {
        if(status[i]==false) prime.push_back(i);
    }
}

long long int EulerPhi(long long int n)
{
    long long  int res=n;
    long long int sq=sqrt(n);

    for(long long int i=0; i<prime.size() and prime[i]<=sq; i++)
    {
        if(n%prime[i]==0)
        {
            while(n%prime[i]==0)
            {
                n=n/prime[i];
            }
            sq=sqrt(n);
            res=res/prime[i];
            res=res*(prime[i]-1);
        }

    }
    if(n!=1)
    {
        res=res/n;
        res=res*(n-1);
    }
    return res;
}

int main()
{
    sieve();
    long long int n;

    while(cin>>n)
    {
        cout<<EulerPhi(n)<<endl;
    }
}

No comments:

Post a Comment