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 theforloop has finished.I am thinking of adding an addition
ifstatement in theforloop 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 theforloop. However, the cost comes at adding an additionalifstatement for every iteration in theforloop.How should I go about deciding if the additional
ifstatement is worth the cost?
counterfor anything else. replacecounter ++byreturn truealtogether. if you reach the end of the loop,return false(also you call itcounterandcount. that would not work) \$\endgroup\$