-1
這裏是我的代碼打印Prime no。在給定的範圍內, 如何優化時間複雜度。 以及如果用戶在輸入中提供了一個字符,該如何處理。目前,如果我輸入任何輸入的字符就說明這個找到第N個素數,如何優化此代碼
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextLong(Scanner.java:2265)
at java.util.Scanner.nextLong(Scanner.java:2225)
at NthPrimeNo.main(NthPrimeNo.java:23)
下面是代碼
public class NthPrimeNo {
public static void main(String[] args) {
long j,k,t=0;
int count =0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the starting point of the range: ");
long N1 = sc.nextLong();
System.out.println("Enter the Ending point of the range: ");
long N2 = sc.nextLong();
System.out.print("Enter n to compute the nth prime number: ");
long nth = sc.nextLong();
if((nth>0) && (N2>N1) && (N1<1500000) && (N2<1500000)) {
for(long i=N1;i<=N2;i++) {
for(j=1,k=0;j<=i;j++) {
if(i%j==0)
k++;
}
if(k==2) {
t++;
if(t==nth) {
System.out.println(i);
count=1;
break;
}
}
}
if(count==0) {
System.out.print("\n no prime number is present at this index");
}
} else {
System.out.println("Invalid Input");
}
}
}
如果您希望人們嘗試讀取您的代碼,請問您是否可以修復縮進問題 – khelwood
分配長度爲'N2 + 1'的數組;使用[Eratosthenes篩選](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)查找所有素數;然後從元素'N1'開始,直到找到第n個素數。 –
@see discussion http://stackoverflow.com/questions/453793/which-is-the-fastest-algorithm-to-find-prime-numbers –