Reputation: 1165
Print out the prime numbers less than a given number N. For bonus points your solution should run in N*log(N)
time or better. You may assume that N is always a positive integer.
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Each test case will contain an integer n < 4,294,967,295
.
E.g.
10
20
100
Output sample:
For each line of input, print out the prime numbers less than N, in ascending order, comma delimited. (There should not be any spaces between the comma and numbers) E.g.
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
Here is my solution:
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();
}
}
My input is :
10
50
And output is :
2,3,5,7
2,3,5,7,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47
But when i submit this solution they are not accepting this solution.
But when i put content in document like this:
10 50
30
I am trying that java program ignore this 50. How to do it ?
Any better solution then this ? Give me some idea!
Upvotes: 1
Views: 7075
Reputation: 5279
"Your program should accept as its first argument a path to a filename"
You have a hardcoded filename in your solution - use args[0]
instead.
Othwerwise, your solutions looks OK, although there is some room for improvements regarding the efficiency.
Upvotes: 0
Reputation: 4826
To ignore the extra number in your file you can take only the first number of each line.
Your solution is probably not accepted because in your second line you have printed 2,3,5,7
twice (i.e. the primes of the previous line)
See the example below to fix both problems
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
}
Upvotes: 1