I am working on a program that takes input from the user to get an upper limit and then uses a method to calculate all of the prime numbers from 1 to N. I have a working solution, but my head keeps bugging me that it is horribly inefficient.
public ArrayList<Integer> primeNumbers()
{
long startTime = System.nanoTime();
ArrayList<Integer> prime = new ArrayList<Integer>();
ArrayList<Integer> factorList;
for (int i = 2; i <= this.limit; i+=1)
{
factorList = factors(i);
if (factorList.size() == 2 && factorList.contains(1) && factorList.contains(i))
{
prime.add(i);
}
}
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println("The total time was: " + totalTime);
return prime;
}
public ArrayList<Integer> factors(int i)
{
ArrayList<Integer> factor = new ArrayList<Integer>();
for (int a = 1; a <= i; a+=1)
{
for (int b = 1; b<=i; b+=1)
{
if (a*b == i)
{
if (factor.contains(a) == false)
factor.add(a);
if (factor.contains(b) == false)
factor.add(b);
}
}
}
return factor;
}
Although the code above works, it seems to go very slowly for
this.limit
values above 3500. Any ideas on how I could improve the efficiency, or am I just being paranoid? Help appreciated.