
primes array list
By: a guest on
Nov 11th, 2015 | syntax:
Java | size: 1.52 KB | views:
4 | expires: Never
package primeFinder;
import java.util.Scanner;
import java.util.ArrayList;
public class PrimeFinder {
public static void main(String[] args){
double timeS, timeE;
double timeT;
Scanner input=new Scanner(System.in);
for(;;){
System.out.println("enter a positive integer greater than 1 to find all the primes less than it enter \"0\" to qutit");
long n=input.nextLong();
if (n<0||n==1){
System.out.println("enter a number greater than 1");
}
else if (n==0){
System.exit(0);
}
else{
System.out.println("valid number entered primes up to "+n+" are:");
timeS=System.currentTimeMillis();
primesToN(n);
timeE=System.currentTimeMillis();
timeT=(timeE-timeS)/1000;
System.out.println("it took "+timeT+" S to calculate primes up to "+n);
}
}
}//end of main
public static void primesToN(Long n){
ArrayList<Long> primes=new ArrayList<Long>();
primes.add((long) 2);
long last=2;
System.out.print("2, ");
boolean print=false;
int count=0;
for(long i=3;i<=n;i++){
for(int x=0;x<=primes.indexOf(last);x++){
if(i%primes.get(x)==0){
print=false;
break;
}
else{
print=true;
}
}
if(print&&count!=4&&i!=n){
primes.add(i);
last=i;
System.out.print(i+", ");
count++;
}
else if(print&&i!=n){
primes.add(i);
last=i;
System.out.println(i+", ");
count=0;
}
print=false;
}
}//end of primesToN
}//end of prime finder