In this post, we will see how we can check if a number is prime or not
Logic
A number is prime, if it has NO divisors other than 1 or itself [in other words, it should not be divisible by any number in between 1 and itself]
e.g
5 => is a prime number [5 is not divisible by any number in between 1 and 5, i.e not divisible by 2/3/4]
9 => is NOT a prime number [9 is divisible by 3]
Implementation
num = 9 # num = int(input("Enter a number: ")) if num > 1: for i in range(2, num // 2): if (num % i) == 0: print(num, "is not a prime number") print(num, "is divisible by", i) break else: print(num, "is a prime number")
num // 2 => divide with 2 (discard remainder)
Used num // 2 => we are checking divisibility half way of the number [no need to check full range]
If interested the implementation in java, refer here