[英]Print out prime Number less than a given number N
打印出少於給定數字N的質數。要獲得加分,您的解決方案應在N*log(N)
時間或更長時間內運行。 您可以假設N始終是一個正整數。
輸入樣本:
您的程序應將文件名路徑作為其第一個參數。 該文件中的每一行都是一個測試用例。 每個測試用例將包含一個整數n < 4,294,967,295
。
例如
10
20
100
輸出樣本:
對於輸入的每一行,以升序打印輸出小於N的質數,以逗號分隔。 (逗號和數字之間不應有空格)例如
2,3,5,7
2,3,5,7,11,13,17,19
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
這是我的解決方案:
public class problem1 {
public static void main(String [] args) throws Exception
{
File f=new File("C://Users/Rahul/Documents/Projects/r.txt");
FileReader fr=new FileReader(f);
List<Integer> l=new ArrayList<>();
int p;
BufferedReader br = new BufferedReader(fr);
String s;
while( (s= br.readLine()) != null ) {
int a=Integer.parseInt(s);
for(int i=2;i<a;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
l.add(i);
}
String st=l.toString();
st=st.replaceAll("\\[", "").replaceAll("\\]", "").replace(", ", ",");
System.out.print(st);
System.out.println("\t");
}
fr.close();
}
}
我的輸入是:
10
50
輸出為:
2,3,5,7
2,3,5,7,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47
但是,當我提交此解決方案時,他們不接受此解決方案。
但是當我將內容放在這樣的文檔中時:
10 50
30
我正在嘗試該Java程序忽略此50。該怎么做?
還有更好的解決方案嗎? 給我一些想法!
要忽略文件中的多余數字,您只能使用每行的第一個數字。
您的解決方案可能不被接受,因為在第二行中,您已經兩次打印了2,3,5,7
(即前一行的素數)
請參閱下面的示例來解決這兩個問題
while( (s= br.readLine()) != null ) {
String [] numbers = s.split(" "); // split the line
int a = Integer.parseInt(numbers[0]); // take only the first one
....
System.out.print(st);
System.out.println("\t");
l.clear(); // clear the list before trying to find primes for the new line
}
“您的程序應將文件名路徑作為第一個參數”
解決方案中包含硬編碼的文件名-請改用args[0]
。
否則,您的解決方案看起來還可以,盡管在效率方面還有一些改進的余地。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.