[英]is there some solution to reduce the time complexity of a program in java?
问题是
给定一个数字“N”。 任务是找到每个数字都是素数(<10)的第 N 个数字,即 2、3、5、7。换句话说,你必须找到这个序列的第 n 个数字:2、3、5、7、22 , 23,.. 等等。
我正在尝试超出时间限制的以下代码。
import java.io.*;
import java.util.*;
class Main {
public static boolean AlldigitsPrime(int m){
for(; m>0;){
int dig=m%10;
if(dig!=2 && dig!=3 && dig!=5 && dig!=7){
return false;
}
m/=10;
}
return true;
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0; i<t; i++){
int n=sc.nextInt();
int count=0;
for(int j=2; j>=2 ; j++){
if(AlldigitsPrime(j)){
count++;
if(count==n){
System.out.println(j);
break ;
}
}
}
}
}
}
您几乎可以直接计算第 n 个数。 这个想法是将n
转换为一个新的数字系统,其中没有数字包含 0 数字(除了被忽略的前导数字),但仅包含数字 1 到 4。即:1 -> 1, 4 -> 4 , 5 -> 11, 6 -> 12, 9 -> 21 等等。 最后一步是将每个数字(1 到 4)替换为其对应的素数(2、3、5 或 7)。
虽然我通常不会给出家庭作业的示例代码,但因为它有点复杂,我将展示解决方案:
public int convert(int n) {
if (n < 1) throw new IllegalArgumentException("n must be positive but was " + n);
int[] primes = {2,3,5,7};
int result = 0;
int power = 1;
do {
int digit = (n-1) % 4 + 1; // we don't want 0es
result += primes[digit - 1] * power;
power *= 10;
n = (n-1) / 4; // take the 'removed' 0es into consideration
} while (n > 0);
return result;
}
当然,在循环的前两行中加减 1 是不必要的,但我将其保留在那里以在计算数字时突出显示 0 的“删除”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.