public class RunnableThreadPrimeNumber implements Runnable
{
private long startNum;
private long endNum;
private Thread t;
RunnableThreadPrimeNumber(long start , long end )
{
t = new Thread(this);
this.startNum = start;
this.endNum = end;
t.start();
}
public void run()
{
for ( int i = start ; i <= last ; i++)
{
if (isPrime(i) == true)
{
System.out.println(i + " is prime")
}
}
}
private boolean isPrime(long n)
{
int counter = 0;
for (int i = 2 ; i < n / 2 ; i++)
{
if ( n % i == 0 )
{
counter ++;
}
}
if ( count > 0 )
{
//number is prime
return true;
}
else
{
//number is not prime
return false;
}
}
public static void main(String[] args)
{
RunnableThreadPrimeNumber(2000,4000);
RunnableThreadPrimeNumber(4001,6000);
}
}
Questions:
Is there any way to improve this algorithm which checks if a given number is prime? The improvement can be anything from space to running time complexity.
For my function
isPrime(long n)
, I am currently looping through every possible number less than half the input number and returning true or false only after thefor
loop has finished.I am thinking of adding an addition
if
statement in thefor
loop which checks if the variable counter is greater than 0. If it's greater than 0, immediately return true. The advantage to this approach is that for some numbers, I can immediately return true/false without needing to finish thefor
loop. However, the cost comes at adding an additionalif
statement for every iteration in thefor
loop.How should I go about deciding if the additional
if
statement is worth the cost?
counter
for anything else. replacecounter ++
byreturn true
altogether. if you reach the end of the loop,return false
(also you call itcounter
andcount
. that would not work) \$\endgroup\$