The previously created "Program to determine whether a number entered in Python is a prime number" has a function that performs prime factorization when it is a composite number. I added it.
Recalling the method of prime factorization that I learned when I was in elementary school, I decided to continue dividing from the smallest prime number. Specifically, create a prime number list using SymPy's primerange and continue to divide by a divisible number from that list. Then, when the division was performed to the end of the prime number list, it was finished.
from sympy import primerange
inn = n = int(input("Enter the number you want to check if it is a prime number.>> "))
primlist = list(primerange(2,(inn+1) / 2)) #1
yaku = []
for i in primlist:
while n % i == 0: #2
n /= i
yaku.append(i) #3
if not yaku: #4
print(n, "Is a prime number.")
else:
print(inn, "Is a composite number, and when factored into prime factors",yaku, "is.")
When I first programmed, the range of the prime number list created by primerange () was the same as last time, "primerange (2, int (n ** (1/2)) + 1)". Then, when the input integer was "2 x prime number", only 2 was added to yaku, and there was a problem that it could not be factored accurately. Specifically, when you enter a number such as 14 (2 × 7), the result is "14 is a composite number, and when factored into prime factors, it is [2]. ] Has come out. Therefore, I set the range of the prime number list to "prime range (2, (inn + 1) / 2)". By doing this, I decided to solve the problem I mentioned earlier. At this time, by adding +1 to inn, a prime number list can be created up to a prime number even with an integer of "2 x prime number". Specifically, when 14 is entered, it becomes primerange (2, 7.5), so the content of primelist becomes [2, 3, 5, 7]. If +1 is not done, it will be primerange (2, 7), so the contents of primelist will be [2, 3, 5], and 7 will not be included in the result of prime factorization, so accurate prime factorization Will not be possible.
If the range of prime number list creation is too wide and the integers entered are large (7 digits or more), the calculation speed will drop immediately. Therefore, I would like to improve the range setting and prime factorization method a little. Thank you for reading to the end.
Recommended Posts