A positive integer with no divisor outside of one and its number itself.
Well, to put it simply, it is a number that can only be divided by 1 and yourself. In other words, it is a number that "has only two divisors". Other numbers are called composite numbers.
So for the time being, I will write a program that displays prime numbers from 1 to 10.
n_list = range(2, 10)
for i in range(2, int(10 ** 0.5) + 1):
n_list = [x for x in n_list if (x == i or x % i !=0)]
for j in n_list:
print(j)
#Execution result
2
3
5
7
Determine if what is assigned to N is a prime number
def calc_prime(N):
for p in range(2, N):
if N % p == 0:
return str(N) + ' is composit'
return str(N) + ' is PRIME!!'
calc_prime(7)
#Execution result
'7is PRIME!!'
A function that displays prime numbers up to N, where N is a natural number
def calc_prime(N):
n_list = range(2, N)
for i in range(2, int(N ** 0.5) + 1):
n_list = [ x for x in n_list if (x == i or x % i !=0)]
for j in n_list:
print(j)
calc_prime(10)
#Execution result
2
3
5
7
Determine if the natural number assigned to n is a prime number.
n = 7
for p in range(2, n):
if n % p == 0:
print(str(n) + ' is composite.')
break
else:
print(str(n) + ' is PRIME!!')
#Execution result
7 is PRIME!!
This time I wrote programming to judge prime numbers. I'm not very familiar with it, but it seems that there are various ways to determine prime numbers, so if you are interested, please check it out. Also, I think there is a way to speed up the calculation, so if you are interested, please implement it.
Recommended Posts