用欧拉函数来计算从1~n中与n互质的整数的个数
用欧拉函数来计算从1~n中与n互质的整数的个数
一、欧拉函数是什么?
1.欧拉函数
图 1.1欧拉函数
两个数互质即两个数的公约数只有1。
2.数据演示
即:1 2 3 4 5 6中1和5都与6互质
图1.2公式
我们具体求每个函数的欧拉公式就是采用这个公式
二、代码如下
1.问题描述
给定n个数,分别求出每个数的欧拉函数
package AcWing;
import java.io.*;
public class 欧拉函数 {
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static void main(String[] args) throws Exception{
int n = nextInt();
while(n-- > 0){
int x = nextInt();
int res = x;
//还是分解质因数的过程
for(int i =2; i < x/i;i++){
if(x % i == 0){
while (x % i == 0){
x /= i;
}
//N = N(1- 1/p)=N(p-1)/p
//主要还是运用题目中给的公式变形
res = res *(i-1)/i;
}
}
//最大的那个质因数
if(x > 1){
res = res *(x - 1) / x;
}
pw.println(res);
}
pw.flush();
}
public static int nextInt()throws Exception{
st.nextToken();
return (int)st.nval;
}
public static String nextLine()throws Exception{
return br.readLine();
}
}
2.读入数据
3
3
6
8
3.代码运行结果
2
2
4
运行样例解释:
与3互为质数:1、2
与6互为质数:1、5
与8互为质数:1、3、5、7
总结
用欧拉函数来计算从1~n中与n互质的整数的个数,主要还是欧拉公式的运行和求质因数的过程。