// CodeEval Prime Numbers
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) {
prime_less.main(args);
}
}
class prime_less {
public static void main(String[] args) {
CodeEvalGetInput(args[0]);
//CodeEvalGetInput("e:\\zin.txt");
}
public static void CodeEvalGetInput(String arg) {
try {
File file = new File(arg);
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
while ((line = in.readLine()) != null) {
String[] lineArray = line.split("\\s");
if (lineArray.length > 0) {
// Process line of input Here
Process(lineArray);
}
}
} catch (IOException e) {
System.out.println("File Read Error: " + e.getMessage());
}
}
private static void Process(String[] lineArray) {
long N = Long.valueOf(lineArray[0]);
List<Long> pp = GetPrimeNumsLessThanOrEqual2(N - 1);
for (int i = 0; i < pp.size(); i++) {
if (i > 0)
System.out.print(",");
System.out.print(pp.get(i));
}
System.out.println("");
}
public static List<Long> GetPrimeNumsLessThanOrEqual2(long maxNum) {
List<Long> p = new ArrayList<Long>();
if (maxNum < 2)
return p;
p.add(2L);
for (long j = 3; j <= maxNum; j += 2) {
boolean isPrime = true;
int N = p.size();
for (int i = 0; i < N; i++) {
long pp = p.get(i);
if (pp * pp > j)
break;
if (j % pp == 0) {
isPrime = false;
break;
}
}
if (isPrime)
p.add(j);
}
return p;
}
}
Hi I have written my code in java in eclipse, when I run it, it shows correct output. Bu when uploaded on code_eval I get error of file not found. I also changed my class to Main. do we also have to upload the text file with it?
ReplyDeletehere is my code
import java.io.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class prime_numbers {
public static void main(String args[]){
BufferedReader br = null;
String strLine = "";
//if the file is not readable, catching exceptions
try {
//File file = new File(args[0]);
br = new BufferedReader( new FileReader("file"));
//reads the file line to line
while( (strLine = br.readLine()) != null){
int num = Integer.parseInt(strLine);
//call the function to print prime until num
printPrime(num);
System.out.println();
}
} catch (FileNotFoundException e) {
System.err.println("Unable to find the file" + e.getMessage());
} catch (IOException e) {
System.err.println("Unable to read the file" + e.getMessage());
}
}
//prints the prime numbers till a limit
public static void printPrime(int number){
for(int i = 2; i<=number; i++){
//print prime numbers only
if(isPrime(i)){
System.out.print(i);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<= Math.sqrt(number); i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
//this doesn't print ',' in front of 2
if(number != 2){
System.out.print(",");
}
return true; //number is prime now
}
}
Please help