In this article A program that determines whether the input value (n) is a prime number or not. I will write.
A prime number is a natural number greater than 1 that has only one positive divisor and itself. See: prime numbers-Wikipedia
(1) If it is 1 or less or 2, describe whether it is a prime number. (2) If it is 3 or more, loop from 2 to n and check if there is a divisible number. If it is divisible, it is not a prime number. ③ Call the function and display the result.
** There was an error in the case of an integer greater than or equal to 3, so I corrected it **
If False, it is not a prime number. If True, a prime number.
prime_num.py
def is_prime(n):
#1 or less is not a prime number
if n <= 1:
return False
#2 is a prime number
if n == 2:
return True
If it is divisible, it is not a prime number
prime_num.py(2)
def is_prime(n):
#1 or less is not a prime number
if n <= 1:
return False
#2 is a prime number
if n == 2:
return True
#Even numbers other than 2 are not prime numbers
if n % 2 == 0:
return False
#For odd numbers of 3 or more, prime numbers unless divisible by all odd numbers up to the square root
return all(n % i != 0 for i in range(3, int(n**0.5) + 1, 2))
If False, it is not a prime number. If True, it is a prime number.
prime_num.py(3)
def is_prime(n):
#1 or less is not a prime number
if n <= 1:
return False
#2 is a prime number
if n == 2:
return True
#Even numbers other than 2 are not prime numbers
if n % 2 == 0:
return False
#For odd numbers of 3 or more, prime numbers unless divisible by all odd numbers up to the square root
return all(n % i != 0 for i in range(3, int(n**0.5) + 1, 2))
number = int(input("Natural number →"))
if is_prime(number):
print(f"{number}Is a prime number.")
else:
print(f"{number}Is not a prime number.")
Execution result
number = 1
→ 1 is not a prime number.
number = 5
→ 5 is a prime number.
The result is reflected.
This time, I wrote a program to judge whether it is a prime number in Python.
In this program, the larger n is, the longer the calculation becomes. I would like to find more efficient code.
Recommended Posts