মঙ্গলবার, ২৮ আগস্ট, ২০১৮

Relatively prime less than n (Relatively prime means gcd between n and this number is 1)

How many positive integers less than n are relatively prime to n? Two integers a and b are relatively prime if there are no integers x > 1, y > 0, z > 0 such that a = xy and b = xz.
For 7 ans is  6 ---- 1,2,3,4,5,6
For 12 ans is 4------1,5,7,11 
GCD of n and less than n is 1


#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int main()
{
    int i,n,res;
    while(scanf("%d",&n)&&n!=0)
    {
        if(n==1)
            printf("%d\n",0);
        else
        {
            res=n;
            for(i=2;i*i<=n;i++)
            {
                if(n%i==0)
                {
                    res=res/i*(i-1);//cout<<res<<endl;
                    while(n%i==0)
                    n/=i;
                }
            }
            if(n!=1)
            {
                res=res/n*(n-1);
            }
            printf("%d\n",res);
        }
    }
    return 0;
}

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন

Factorization with prime Sieve

vector <int> prime; char sieve[1000009]; int N=1000009; void primeSieve ( ) { sieve[0] = sieve[1] = 1; prime.push_back(2); ...