Poj 2407 Relatives.

Source: Internet
Author: User

At first glance, we can see that the Euler's function is used. The formal meaning of the Euler's function description. According to the introduction to algorithms, Euler's function can filter prime numbers from 0 to n-1.
The formula n contains (1-1/p), where p is the prime factor of n, which can be intuitively understood. However, this formula is converted to another form during calculation.
:

However, we need to consider this question. It is possible that n is a large prime number. If a factor is directly decomposed, it will time out. What should I do? I can only judge whether n has become
If it is a prime number, multiply the answer by n-1. In order to speed up the judgment, I used a 5 MB space to create a prime number table. numbers larger than 5000000 can only be judged cyclically.

The Code is as follows. Pay attention to the Code section of the Euler's function:
# Include <stdio. h>
# Include <math. h>
# Define MAX (5000000)
Bool bPrime [MAX]; // false indicates the prime number

Void InitPrime ()
{
BPrime [0] = bPrime [1] = true;
Int nMax = sqrt (double) MAX) + 1;
For (int I = 2; I <= nMax; ++ I)
{
If (! BPrime [I])
For (int j = I * 2; j <MAX; j + = I)
{
BPrime [j] = true;
}
}
}

Bool IsPrime (int nN)
{
If (nN <MAX)
{
Return! BPrime [nN];
}
Else
{
Int nMax = sqrt (double) nN) + 1;
For (int I = 2; I <= nMax; ++ I)
{
If (nN % I = 0)
{
Return false;
}
}
Return true;
}
}

Int main ()
{
Int nN;

InitPrime ();
While (scanf ("% d", & nN), nN)
{
If (nN = 1) {printf ("0 \ n"); continue ;}
Int nAns = 1;
For (int I = 2; I <= nN; ++ I)
{
If (IsPrime (nN ))
{
NAns * = nN-1;
Break;
}
If (nN % I = 0)
{
NAns * = I-1;
NN/= I; www.2cto.com
While (nN % I = 0)
{
NAns * = I;
NN/= I;
}
}
}
Printf ("% d \ n", nAns );
}

Return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.