问题
To check if a number is prime or not, the naive way is to try dividing the number by 2 thru n, and if any operation gets remainder as 0, then we say the given number is not prime. But its optimal to divide and check only till n/2 (am aware much better way is till sqrt(n) ), I want to know the reason for skipping the second half.
say if we need to check number 11 is prime or not, 11/2 = 5. if we do 11/6 or 11/7 or 11/8 or 11/9 or 11/10 in neither of these cases we get remainder as 0. So is the case for any given number n.
Is the reason for avoiding second half this? "if you divide the given number by any number which is more than given number's half, remainder will never be 0 Or in other words, none of the numbers which are more than the given number's half can divide the given number"
Please help me know if am right
回答1:
Because, the smallest multiple that will not make it a prime is 2. If you have checked all the numbers from 0 to n/2, what multiple is left that could possibly work? If multiple by 2 is bigger than n, then a multiple of 3 or 4 etc will also be bigger than n.
So the largest factor for any number N must be <= N/2
So yes take N/2, and check all integers smaller or equal to N/2. So for 11 you would check all integers smaller than 5.5, i.e. 1, 2, 3, 4 and 5.
The square root is explained here: Why do we check up to the square root of a prime number to determine if it is prime?
And this question has been asked before.
回答2:
To factor the number n
you have to divide by two other integers, call them a
and b
. Both of those numbers need to be 2 or larger, so it doesn't make any sense to check numbers larger than n/2
, they couldn't possibly divide evenly.
And yes, sqrt(n) is more efficient, because if a
is larger than sqrt(n) then b
must be smaller, and you'd have already checked it.
来源:https://stackoverflow.com/questions/39429564/to-find-a-number-is-prime-why-checking-till-n-2-is-better-what-is-the-reason-f