MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / get_factors

Function get_factors

maths/gcd_of_n_numbers.py:9–60  ·  view source on GitHub ↗

this is a recursive function for get all factors of number >>> get_factors(45) Counter({3: 2, 5: 1}) >>> get_factors(2520) Counter({2: 3, 3: 2, 5: 1, 7: 1}) >>> get_factors(23) Counter({23: 1}) >>> get_factors(0) Traceback (most recent call last): ...

(
    number: int, factors: Counter | None = None, factor: int = 2
)

Source from the content-addressed store, hash-verified

7
8
9def get_factors(
10 number: int, factors: Counter | None = None, factor: int = 2
11) -> Counter:
12 """
13 this is a recursive function for get all factors of number
14 >>> get_factors(45)
15 Counter({3: 2, 5: 1})
16 >>> get_factors(2520)
17 Counter({2: 3, 3: 2, 5: 1, 7: 1})
18 >>> get_factors(23)
19 Counter({23: 1})
20 >>> get_factors(0)
21 Traceback (most recent call last):
22 ...
23 TypeError: number must be integer and greater than zero
24 >>> get_factors(-1)
25 Traceback (most recent call last):
26 ...
27 TypeError: number must be integer and greater than zero
28 >>> get_factors(1.5)
29 Traceback (most recent call last):
30 ...
31 TypeError: number must be integer and greater than zero
32
33 factor can be all numbers from 2 to number that we check if number % factor == 0
34 if it is equal to zero, we check again with number // factor
35 else we increase factor by one
36 """
37
38 match number:
39 case int(number) if number == 1:
40 return Counter({1: 1})
41 case int(num) if number > 0:
42 number = num
43 case _:
44 raise TypeError("number must be integer and greater than zero")
45
46 factors = factors or Counter()
47
48 if number == factor: # break condition
49 # all numbers are factors of itself
50 factors[factor] += 1
51 return factors
52
53 if number % factor > 0:
54 # if it is greater than zero
55 # so it is not a factor of number and we check next number
56 return get_factors(number, factors, factor + 1)
57
58 factors[factor] += 1
59 # else we update factors (that is Counter(dict-like) type) and check again
60 return get_factors(number // factor, factors, factor)
61
62
63def get_greatest_common_divisor(*numbers: int) -> int:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected