Advertisement
acclivity

pyFindFactorsUsing3Methods

Jan 17th, 2022
853
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.77 KB | None | 0 0
  1. # Find divisors of a user-chosen integer
  2. # THREE METHODS
  3. # Mike Kerry - Jan 2022 - acclivity2@gmail.com
  4.  
  5. # Version 1 (Simplest)
  6.  
  7. # Start by getting an integer from the user.
  8. # Note that as input() ALWAYS returns a string (like "1234") we need to convert it to an integer
  9. # before we can do any arithmetic on it. The conversion is done by int() wrapped around input()
  10. # BUT: if the user types anything non-numeric, our script will crash. We will fix that in version 2
  11. number = int(input("Please choose a number to divide: "))
  12.  
  13. # Here we define an empty list.
  14. # We need an empty list to start with, as we will be appending each divisor to it
  15. divisorList = []
  16.  
  17. # This for loop will give us divisors from 1 up to and including the value of number (not beyond)
  18. for div in range(1, number + 1):
  19.  
  20.     # number % div gives us the remainder when number is divided by div
  21.     if number % div == 0:           # If the remainder is zero ...
  22.         divisorList.append(div)     # then div is a true divisor of number. Append it to results list
  23.  
  24. # The loop from 1 to number has finished. Now we can print the results list
  25. print(divisorList)
  26.  
  27. # ================ END OF VERSION 1 ================
  28.  
  29. # ========================================================
  30. # Version 2. Better more "Pythonic" code
  31.  
  32. # In this version, we will verify that what the user types is numeric
  33. # In our script version 1 above, the script would crash if the user either just hit enter,
  34. # or typed any characters other then 0 through 9. This version avoids such a crash
  35.  
  36. # First we code a loop which will keep looping until we get a good integer from the user
  37. while True:
  38.     # get the user input as a string variable
  39.     userin = input("Please choose a number to divide: ")
  40.  
  41.     # if the string variable contains only digits 0 to 9, then we break out of this loop
  42.     if userin.isdigit():
  43.         break
  44.  
  45.     # The user did not type a valid numeric input. Ask then to type again, and keep looping
  46.     print("Invalid integer. Please enter again\n")
  47.  
  48. # Now we know that userin contains numeric data, so we can convert it safely to an integer (number)
  49. number = int(userin)
  50. # For this version, we don't need an empty results list, as we will print the divisors as we go
  51.  
  52. # Same loop as version 1. "div" will contain integers 1 to number in turn. Not beyond.
  53. for div in range(1, number + 1):
  54.  
  55.     # "if not number % div": this computes the remainder and tests if there is no result (not ... i.e. 0)
  56.     # This is "more Pythonic" than saying "if number % div == 0"
  57.     if not number % div:
  58.         # Now we can print this divisor, but follow it with a space, not end-of-line
  59.         # This effectively is an incomplete print ... we are just building up a print line
  60.         print(div, end=", ")
  61.  
  62. # Our divisor loop has finished.
  63. # Now we can do the final stage of actually printing the line we were building
  64. print()
  65.  
  66. # ========================== END OF VERSION 2 =====================
  67.  
  68.  
  69. # ======================== VERSION 3 =========== MORE EFFICIENT =============
  70. # Now we realise that we only need to divide 'number' by integers up to the square root of 'number'
  71. # We will use the Python built-in function divmod() which gives us both the quotient and the remainder
  72. # This will be MUCH faster for large numbers.
  73. # e.g. for 12345678 we only need do 3513 divisions instead of over 12 million
  74.  
  75. # Code a loop that will keep repeating the whole script until the user types a non-numeric
  76. while True:
  77.     # Get the input from the user as a string. This will always be safe (won't crash)
  78.     userin = input("Enter a number to find its divisors:\n(Any non-integer to quit) ")
  79.  
  80.     # In this version, if the user types anything non-numeric, we will simply terminate the script
  81.     if not userin.isdigit():
  82.         break                       # break out of the while loop, and end the script
  83.  
  84.     number = int(userin)            # convert user input from a string variable to an integer variable
  85.  
  86.     # For this efficient version, we will go back to using a list for our results
  87.     # But we need two lists, one for divisors, one for quotients
  88.     # The reason will become clear later (I hope!)
  89.     divisorList = []
  90.     quotientList = []
  91.  
  92.     # Now we compute the square-root of number. Note that we need an integer result, not a float
  93.     limit = int(number ** 0.5)      # limit is the nearest integer below or equal to the square-root
  94.  
  95.     # Loop from 1 up to limit inclusive (not beyond)
  96.     for div in range(1, limit + 1):
  97.  
  98.         # The very handy divmod() function gives us the quotient and remainder all in one go
  99.         q, r = divmod(number, div)
  100.         # q is the quotient of number divided by div
  101.         # r is the remainder when number is divided by div
  102.  
  103.         if not r:                       # if the remainder is zero ...
  104.             divisorList.append(div)     # append the divisor to our results list
  105.             quotientList.append(q)      # append the quotient to the quotient list
  106.             # The quotient is the second factor involved in this division
  107.             # e.g. if number is 27 and div is 3, the quotient is 9 and both 3 and 9 are factors of 27
  108.             # we don't need to divide by 9. We already know the factors 3 and 9
  109.  
  110.     # OK, we have computed all the divisors up to the square root. We now need to append all the
  111.     # quotients to our results list, but putting them in the correct order (they are currently reversed)
  112.     # we use the extend() method to concatenate the two lists
  113.     divisorList.extend(quotientList[::-1])          # [::-1] reverses the quotient list
  114.     print(divisorList)
  115.  
  116.  
  117. # Result
  118. # Enter a number to find its divisors: 12345678
  119. # [1, 2, 3, 6, 9, 18, 47, 94, 141, 282, 423, 846,
  120. # 14593, 29186, 43779, 87558, 131337, 262674, 685871, 1371742, 2057613, 4115226, 6172839, 12345678]
  121.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement