primality-test

Program that checks if a number is prime number

杀马特。学长 韩版系。学妹 提交于 2019-11-26 18:41:07
问题 Hello I have created this program to check if a number is a prime number. It works but for some reason says that 999 is a prime number. Where is my mistake. It would be great if someone explained. Thank You! Here is my program: number = raw_input('Enter a Number: ') nnumber = int(number) prime_range = range(2, nnumber) for x in prime_range: if nnumber % x == 0: print 'Not a Prime Number!' break else: print 'Prime Number!' break 回答1: Trace it. x starts with 2 , then tests 999 % 2 ; it is 1 ,

Why do we check up to the square root of a prime number to determine if it is prime?

旧巷老猫 提交于 2019-11-25 22:34:50
问题 To test whether a number is prime or not, why do we have to test whether it is divisible only up to the square root of that number? 回答1: If a number n is not a prime, it can be factored into two factors a and b : n = a * b If both a and b were greater than the square root of n , then a * b would be greater than n . So at least one of those factors must be less than or equal to the square root of n , and if we can't find any factors less than or equal to the square root, n must be prime. 回答2: