python Method of Finding Factor and Prime Factor

  • 2021-07-26 08:27:21
  • OfStack

Recently, a schoolmate asked me some questions about solving prime factors. While helping him solve the problems, he also tried to write several scripts with similar effects. There are many different ideas. The following are related scripts.


n = int(input("input number: ")) #  Enter a number 
fac = [] #  Definition 1 List storage factor 
for i in range(2, n): #  The logic here and you 1 Sample 
  if n % i == 0:
    fac.append(i) #  If it is a factor, put it in 
    continue
  else:
    pass
if len(fac) == 0: #  Judge 1 Under 
  print("prime!")
else:
  print(fac)

This is the practice of putting all factors in one list.


def isprime(n): # 1 A method to determine a prime number, if it is a prime number, it returns this number, and if it is not a prime number, it returns nothing 
  for i in range(2, n):
    if n % i == 0:
      break
  else:
    return n 
 
num = int(input("input number: ")) #  Input 1 Number, save as num
i = 1 #  Set the Sentinel variable to 1
if num >= 2: #  Judge first num Whether it meets the judgment conditions 
 
  while i <= num: #  Pay attention here 1 Be sure to use while Statement loop, because the sentinel variable will be updated last 
    i += 1 # i = i + 1  Attempt to traverse from 1 To num All numbers of 
    if num % i == 0: #  If i Is his factor 
      print(isprime(i)) #  First look at whether this factor is a prime number, and then output it 
      num = num / i #  Update at this time 1 Under num
      # print("num is %s now!" % num) #  You can look at the present num How much is it 
      i = 1 #  Remember to reset the Sentinel to 1 , so that the loop will be updated, and I 1 Start using for Statement loop, found that it was impossible to start the loop from scratch 
      pass #  Continue 
    else:
      pass #  If i No num Factor of, skipping 
else:
  print("error") #  If the condition is not met, an error will be output 

This is the prime factor decomposition.


Related articles: