HDU - 2654 Become A Hero

Lemon wants to be a hero since he was a child. Recently he is reading a book called “Where Is Hero From” written by ZTY. After reading the book, Lemon sends a letter to ZTY. Soon he recieves a reply.

Dear Lemon,
It is my way of success. Please caculate the algorithm, and secret is behind the answer. The algorithm follows:
Int Answer(Int n)
{
…Count = 0;
…For (I = 1; I <= n; I++)
…{
…If (LCM(I, n) < n * I)
…Count++;
…}
…Return Count;
}
The LCM(m, n) is the lowest common multiple of m and n.
It is easy for you, isn’t it.
Please hurry up!
ZTY

What a good chance to be a hero. Lemon can not wait any longer. Please help Lemon get the answer as soon as possible.
Input
First line contains an integer T(1 <= T <= 1000000) indicates the number of test case. Then T line follows, each line contains an integer n (1 <= n <= 2000000).
Output
For each data print one line, the Answer(n).
Sample Input
1
1
Sample Output
0

题意:
给出下面函数的值
Int Answer(Int n)
{
…Count = 0;
…For (I = 1; I <= n; I++)
…{
…If (LCM(I, n) < n * I)
…Count++;
…}
…Return Count;
}
i与n的最小公倍数比他两个的乘积小说明i与n不互质,也就是说让求小于等于n的与n不互质的数的个数。

思路:可以用欧拉函数求出小于n的与n互质的数的个数,然后用n减去这个数

AC代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;;
const int N = 2000010 ;
int phi[N], prime[N];
int tot;
void Euler()
{
    phi[1] = 1;
    for(int i = 2; i < N; i ++)
        {
        if(!phi[i])
        {
            phi[i] = i-1;
            prime[tot ++] = i;
        }
        for(int j = 0; j < tot && 1ll*i*prime[j] < N; j ++)
        {
            if(i % prime[j]) phi[i * prime[j]] = phi[i] * (prime[j]-1);
            else
            {
                phi[i * prime[j] ] = phi[i] * prime[j];
                break;
            }
        }
    }
}
int main()
{
    int t,n;
    scanf("%d",&t);
    Euler();
    while(t--)
    {
        scanf("%d",&n);
        printf("%d\n",n-phi[n]);
    }
}
发布了261 篇原创文章 · 获赞 14 · 访问量 7423

猜你喜欢

转载自blog.csdn.net/weixin_43244265/article/details/104005565