互质数的个数(欧拉函数+快速幂)
题目描述
给定 a, b,求 1 ≤ x < ab 中有多少个 x 与 ab 互质。由于答案可能很大,你只需要输出答案对 998244353 取模的结果。
输入格式
输入一行包含两个整数分别表示 a, b,用一个空格分隔。
输出格式
输出一行包含一个整数表示答案。
样例输入复制
2 5
样例输出复制
16
思路
第一版代码(超时了)
1 import java.util.*; 2 import java.io.*; 3 // 1:无需package 4 // 2: 类名必须Main, 不可修改 5 6 public class Main { 7 public static void main(String[] args) { 8 Scanner sc = new Scanner(System.in); 9 long a=sc.nextLong(); 10 long b=sc.nextLong(); 11 long n=fast_power(a,b); 12 13 long res=n; 14 for(int i=2;i*i<=n;i++){ 15 if(n%i==0){ 16 res=res/i*(i-1); 17 while(n%i==0){ 18 n=n/i; 19 } 20 } 21 } 22 if(n>1)res=res/n*(n-1); 23 24 System.out.print(res%=998244353); 25 sc.close(); 26 } 27 28 private static long fast_power(long a,long b){ 29 long temp=1; 30 while(b>0){ 31 if(b%2==1){ 32 temp=temp*a; 33 } 34 a=a*a; 35 b=b/2; 36 } 37 return temp; 38 } 39 }
后来看题解,发现还可以简化,所以第二版
单纯改并不对,可能是快速幂不够优化(思考)
运用别人的发现就是快速幂不够
1 private static long fast_power(long a,long b){ 2 long res = 1; 3 while(b>0){ 4 if((b&1)>0){ 5 res = (res*a)%mod; 6 } 7 a = (a*a)%mod; 8 b>>=1; 9 } 10 return res; 11 }
这样就都过了