Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c1abf25

Browse files
Added factors.py
1 parent 061b2cc commit c1abf25

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎factors.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from typing import Optional
2+
3+
4+
class Factors:
5+
@staticmethod
6+
def factors_iteration(number: int, use_while: bool = False) -> list[int]:
7+
factors: list[int] = []
8+
negative_factors: bool = False
9+
if number == 0:
10+
raise ArithmeticError("Factors of zero don't exist.")
11+
elif not isinstance(number, int):
12+
raise ArithmeticError("Factors of non-integers is not supported.")
13+
elif number < 0:
14+
negative_factors = True
15+
if use_while:
16+
i: int = 1
17+
while i < abs(number) + 1:
18+
if abs(number) % i == 0:
19+
factors.append(i)
20+
if negative_factors:
21+
factors.append(-1 * i)
22+
i += 1
23+
else:
24+
for i in range(1, abs(number) + 1):
25+
if abs(number) % i == 0:
26+
factors.append(i)
27+
if negative_factors:
28+
factors.append(-1 * i)
29+
return factors
30+
31+
@staticmethod
32+
def factors_recursion(number: int, next_factor: Optional[int] = None, factors: Optional[list[int]] = None,
33+
negative_factors: bool = False) -> list[int]:
34+
if next_factor is None and factors is None:
35+
factors = []
36+
next_factor = abs(number)
37+
if number == 0:
38+
raise ArithmeticError("Factors of zero don't exist.")
39+
elif not isinstance(number, int):
40+
raise ArithmeticError("Factors of non-integers is not supported.")
41+
elif number < 0:
42+
negative_factors = True
43+
if next_factor == 0:
44+
return list(reversed(factors))
45+
elif abs(number) % next_factor == 0:
46+
if negative_factors:
47+
factors.append(-1 * next_factor)
48+
factors.append(next_factor)
49+
return Factors.factors_recursion(number, next_factor - 1, factors, negative_factors)
50+
51+
52+
if __name__ == '__main__':
53+
input_number = int(input("Enter a non-zero integer: "))
54+
print("Using iteration (for):", Factors.factors_iteration(input_number))
55+
print("Using iteration (while):", Factors.factors_iteration(input_number, use_while=True))
56+
print("Using recursion:", Factors.factors_recursion(input_number))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /