一道Java题,总是时间超限,求正解
答案:3 悬赏:40
解决时间 2021-03-12 02:16
- 提问者网友:玫瑰园
- 2021-03-11 15:07
一道Java题,总是时间超限,求正解
最佳答案
- 二级知识专家网友:洎扰庸人
- 2021-03-11 16:26
你可以看一下 欧拉函数。
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int groupNum = sc.nextInt();
int[] array = new int[groupNum];
for(int i = 0; i < array.length; i++) {
array[i] = sc.nextInt();
}
for(int i = 0; i < array.length; i++) {
//欧拉函数,时间复杂度O(n).
int count = 1;
int temp = array[i];
for(int j = 2; j*j <= temp; j++) {
if(temp %j ==0) {
temp /= j;
count *= (j-1);
while(temp % j == 0) {
temp /= j;
count *= j;
}
}
}
if(temp > 1) count *=(temp -1);
System.out.println(count);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int groupNum = sc.nextInt();
int[] array = new int[groupNum];
for(int i = 0; i < array.length; i++) {
array[i] = sc.nextInt();
}
for(int i = 0; i < array.length; i++) {
//欧拉函数,时间复杂度O(n).
int count = 1;
int temp = array[i];
for(int j = 2; j*j <= temp; j++) {
if(temp %j ==0) {
temp /= j;
count *= (j-1);
while(temp % j == 0) {
temp /= j;
count *= j;
}
}
}
if(temp > 1) count *=(temp -1);
System.out.println(count);
}
}
全部回答
- 1楼网友:蕴藏春秋
- 2021-03-11 19:20
学会用位运算。
图太小
图太小
- 2楼网友:鱼忧
- 2021-03-11 17:55
给链接地址,java速度慢,要试试才知道有没有超时
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯