Last active
December 22, 2024 23:42
-
-
Save StrangeRanger/4f1e22b9e081b50519a40b15644c5297 to your computer and use it in GitHub Desktop.
number_factoring.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# Take a user provided integer and find all of the possible factors for that number. | |
# | |
# Notes: | |
# Does not find the factors of negative numbers. | |
# | |
# Version: v1.1.3 | |
# License: MIT License | |
# Copyright (c) 2020-2021 Hunter T. (StrangeRanger) | |
# | |
######################################################################################## | |
def finding(x): | |
"""Finds and displays all factors of a given integer in a paired format. | |
Args: | |
x (int): The integer for which factors are to be calculated. | |
""" | |
factors = [] | |
i = 0 | |
while i < x: | |
i += 1 | |
if x % i == 0: | |
factors.append(i) | |
first = 0 | |
last = len(factors) - 1 | |
even_odd = len(factors) % 2 | |
if even_odd == 1: | |
factor_length = int(len(factors) / 2 + 1) | |
else: | |
factor_length = int(len(factors) / 2) | |
## Print the corresponding factors side by side. | |
for i in range(factor_length): | |
print("{}*{}".format(factors[first], factors[last])) | |
first += 1 | |
last -= 1 | |
print("\nA total of {} factors of {}".format(len(factors), num)) | |
## Make sure that user input is valid and that any ValueErrors are caught. | |
while True: | |
try: | |
num = int(input("Enter a number: ")) | |
except ValueError: | |
print("Invalid input: only numbers are accepted as input\n") | |
continue | |
if num < 0: | |
print("Invalid input: only positive numbers are accepted as input\n") | |
continue | |
break | |
print("\nFactors of {} are: ".format(num)) | |
finding(num) |
Author
StrangeRanger
commented
Jun 7, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment