

The latter range is based on the fact that a composite number must have a factor less than or equal to the square root of that number. We could have used the range, range(2,num//2) or range(2,math.floor(math.sqrt(num)+1)). In the above program, our search range is from 2 to num - 1. Note: We can improve our program by decreasing the range of numbers where we look for factors. If it is True, num is not a prime number.Outside the loop, we check if flag is True or False. If we find a factor in that range, the number is not prime, so we set flag to True and break out of the loop. We check if num is exactly divisible by any number from 2 to num - 1. Hence, we only proceed if the num is greater than 1.

Numbers less than or equal to 1 are not prime numbers. In this program, we have checked if num is prime or not. But 6 is not prime (it is composite) since, 2 x 3 = 6.Įxample 1: Using a flag variable # Program to check if a number is prime or not are prime numbers as they do not have any other factors. A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number.
