# 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?
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.
0
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 ;
}
``````
0

Experts Exchange Solution brought to you by

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

Commented:
Doug - right, and he could also test for divisibility by 2 outside the loop, and then start i at 3, and do i=i+2 each time, just to test for odd number divisibility (wouldn't step over prime multiples, but it would cut down the loop iterations, which might show some speed benefits if the tested number was really large). ?
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.