1. 程式人生 > >hdu 4135 Co-prime 記

hdu 4135 Co-prime 記

題目連結:Co-prime
Co-prime
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8288 Accepted Submission(s): 3305

Problem Description
Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.

Input
The first line on input contains T (0 < T <= 100) the number of test cases, each of the next T lines contains three integers A, B, N where (1 <= A <= B <= 1015) and (1 <=N <= 109).

Output
For each test case, print the number of integers between A and B inclusive which are relatively prime to N. Follow the output format below.

Sample Input
2
1 10 2
3 15 5

Sample Output
Case #1: 5
Case #2: 10

Hint
In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.

Source
The Third Lebanese Collegiate Programming Contest

Recommend
lcy | We have carefully selected several similar problems for you: 1796 1434 3460 1502 4136

題意:
就是求A到B之間有多少個與N互質的個數
問題分析:
我就是將求尤拉函式的程式碼裡的ans=n換成ans=w(w就是A或B),感覺這個很符合尤拉函式裡面的推到過程,可能有待證明吧。	
沒有AC的語言程式如下:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
typedef long long ll ;

// 得到n的質因子
ll phi(ll n, ll w)
{
    int m=(int)sqrt(n+0.5);
    ll ans=w;
    for(int i=2;i<=m;i++) if(n%i==0)
    {
        if(ans>=i)
            ans=ans/i*(i-1);
        while(n%i==0) n/=i;
    }
    if(n>1)
    {
        if(ans>=n)
            ans=ans/n*(n-1);
    }
    return ans;
}
int main()
{
    ll x, y, n;
    int t;
    scanf("%d",&t);
    int ok=1;
    while(t--)
    {
        scanf("%lld%lld%lld", &x, &y, &n);
        printf("Case #%d: %lld\n",ok++,phi(n,y)-phi(n,x-1));

    }
    return 0;
}