# primenumber using Math.sqrt function and while loop

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
LVL 7
###### Who is Participating?

x
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.

\Commented:
If you can find an integer, A > 1 so that N/A = B, an integer, then N is not prime, since N = A * B.
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.
Commented:
Would this do?  (You can convert the for loop to a while if you really wish).

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