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

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

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.

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)?
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.
Would this do?  (You can convert the for loop to a while if you really wish).


	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 ;

Open in new window

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
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). ?
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

From novice to tech pro — start learning today.