首页 > 代码库 > HDU 4002 Find the maximum(数论-欧拉函数)

HDU 4002 Find the maximum(数论-欧拉函数)

Find the maximum


Problem Description
Euler‘s Totient function, φ (n) [sometimes called the phi function], is used to determine the number of numbers less than n which are relatively prime to n . For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6. 
HG is the master of X Y. One day HG wants to teachers XY something about Euler‘s Totient function by a mathematic game. That is HG gives a positive integer N and XY tells his master the value of 2<=n<=N for which φ(n) is a maximum. Soon HG finds that this seems a little easy for XY who is a primer of Lupus, because XY gives the right answer very fast by a small program. So HG makes some changes. For this time XY will tells him the value of 2<=n<=N for which n/φ(n) is a maximum. This time XY meets some difficult because he has no enough knowledge to solve this problem. Now he needs your help.
 

Input
There are T test cases (1<=T<=50000). For each test case, standard input contains a line with 2 ≤ n ≤ 10^100.
 

Output
For each test case there should be single line of output answering the question posed above.
 

Sample Input
2 10 100
 

Sample Output
6 30
Hint
If the maximum is achieved more than once, we might pick the smallest such n.
 

Source
The 36th ACM/ICPC Asia Regional Dalian Site —— Online Contest
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  4007 4003 4008 4005 4009 
 

题目大意:

给定一个n,问你1~n中,求一个数 x 使得  x/φ(x) 的值最大。


解题思路:

根据欧拉函数的公式,φ(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn)

则:x/φ(x)=p1/(p1-1)*p2/(p2-1)*......*pn/(pn-1)

可以看出项越多x/φ(x)越大,且因子越小x/φ(x)越大,那么只需要2*3*5*7....

考虑到数字很大,所以用JAVA来写,因为JAVA大数吗,你懂的。。


解题代码:

import java.util.*;
import java.math.*;

public class Main {

	public static void main(String[] args) {
		int maxn=2100;
		boolean []isPrime =new boolean[maxn];
		int tol=0;
		int []v=new int[210];
		
		for(int i=0;i<maxn;i++) isPrime[i]=true;  
		for(int i=2;i<maxn;i++){
				if(tol>56) break;
		        if(isPrime[i]) v[tol++]=i;
		        for(int j=0;j<tol && i*v[j]<maxn;j++){  
		            isPrime[i*v[j]]=false;  
		            if(i%v[j]==0) break;  
		        }
		}
		
		//System.out.println(tol);
		//for(int i=0;i<tol;i++) System.out.println(v[i]);
		
		BigInteger []a=new BigInteger[200];
		
		a[0]=new BigInteger("1"); 
		for(int i=1;i<56;i++){
			BigInteger tmp= BigInteger.valueOf(v[i-1]) ;
			//System.out.print(tmp+" ");
			a[i]=a[i-1].multiply(tmp);
			//System.out.println(a[i]);
		}
		
		Scanner scan=new Scanner(System.in);
		int t=scan.nextInt();
		while(t-- >0){
			String str=scan.next();
			BigInteger x=new BigInteger(str);
			BigInteger ans=new BigInteger("2");
			for(int i=1;i<56;i++){
				if(x.compareTo(a[i]) >=0){
					ans=a[i];
				}
				else break;
			}
			System.out.println(ans);
		}
	}

}