The Blue Bridge Cup algorithm improves Euler's function-the complexity is O(n log n)

Question 1541: [Blue Bridge Cup] [Algorithm Improved VIP] Euler Function
Time Limit: 1Sec Memory Limit: 128MB Submitted: 438 Solution: 200 Problem
Description
Given a positive integer n greater than 1 but not more than 2000000, output Euler function , The value of phi(n).
If you don't understand Euler's function, please refer to the hint.

Tip The
Euler function phi(n) is a very important function in number theory, which represents the number of numbers that are relatively prime to n between 1 and n-1. Obviously, we can directly calculate phi(n) by definition.
Of course, there is another calculation method for phi(n).
First, we decompose the prime factors of n, let us set n=p1^a1 * p2^a2 *… * pk^ak (where a^b represents a to the b power, and p1 to pk are k mutually different prime numbers, a1 to ak are all positive integers), then
phi(n)=n(1-(1/p1))(1-(1/p2))...(1-(1/pk)) a
little simplified is
phi (n)=n(p1-1)(p2-1)…(pk-1)/(p1 p2 …*pk)

When calculating, be careful that the intermediate calculation result exceeds the upper bound of the int type, which can be avoided by adjusting the calculation order of the formulas (for example, do the division first)!

Input
Read in the given input file:
a positive integer n per line.
Output Output
the output information to the specified file:
one integer per line represents phi(n).
Sample input
17
Sample output
16

#include<iostream>
using namespace std;
int gcd(int a,int b)
{
    
    
	return b==0?a:gcd(b,a%b); //最大公因数
}

int phi(int x)
{
    
    
	int ans=0;
	for(int i=1;i<=x;i++)
	{
    
    
		if(gcd(i,x)==1) ans++;
	}
	return ans;
}

int main()
{
    
    
	int n;
	cin>>n;
	cout<<phi(n)<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_46232829/article/details/107665606