I would like to write program to know given number is primenumber using Math.sqrt function and while loop. How can i achieve it. Please advise

Experts Exchange Solution brought to you by

Enjoy your complimentary solution view.

Get every solution instantly with Premium.
Start your 7-day free trial.

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Doug

```
public static boolean isPrime(int n) {
for (int i = 2 ; i <= Math.round(Math.sqrt(n)) ; i++) {
// Can we divide i into n exactly?
if (n % i == 0)
return false ;
}
// No factors, then it must be prime
return true ;
}
```

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Java

From novice to tech pro — start learning today.

Experts Exchange Solution brought to you by

Enjoy your complimentary solution view.

Get every solution instantly with Premium.
Start your 7-day free trial.

Could it be that both A and B are greater than sqrt(N)?

No.

sqrt(N) * sqrt(N) = N

If A > sqrt(N) and if B > sqrt(N), then A * B > sqrt(N) * sqrt(N) = N.

That means that one of {A, B} must be < sqrt(N).

That means that if a number N is not prime, then there exists an integer X <= sqrt(N), such that X divides evenly into N.

X = 2

while (X <= sqrt(N))

Is N/X an integer? If so, then N is not prime. Return false.

else X = X+1

end loop

Return true because we did not find an integer X <= sqrt(N) that divides evenly into N, so N must be prime.