FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms/algorithms/backtracking/factor_combinations.py at main · keon/algorithms · GitHub
keon
/
algorithms
Public
Notifications
You must be signed in to change notification settings
Fork
4.7k
Star
25.5k
Code
Issues
2
Pull requests
3
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms
/
algorithms
/
backtracking
/
factor_combinations.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
71 lines (55 loc) · 1.97 KB
Breadcrumbs
algorithms
/
algorithms
/
backtracking
/
factor_combinations.py
Copy path
File metadata and controls
71 lines (55 loc) · 1.97 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Factor Combinations
Given an integer n, return all possible combinations of its factors.
Factors should be greater than 1 and less than n.
Reference: https://leetcode.com/problems/factor-combinations/
Complexity:
Time: O(n * log(n)) approximate
Space: O(log(n)) recursion depth
"""
from
__future__
import
annotations
def
get_factors
(
number
:
int
)
->
list
[
list
[
int
]]:
"""Return all factor combinations of number using iteration.
Args:
number: A positive integer.
Returns:
A list of lists, each containing a valid factorization.
Examples:
>>> get_factors(12)
[[2, 6], [3, 4], [2, 2, 3]]
"""
todo
:
list
[
tuple
[
int
,
int
,
list
[
int
]]]
=
[(
number
,
2
, [])]
combinations
:
list
[
list
[
int
]]
=
[]
while
todo
:
remaining
,
divisor
,
partial
=
todo
.
pop
()
while
divisor
*
divisor
<=
remaining
:
if
remaining
%
divisor
==
0
:
combinations
.
append
(
partial
+
[
divisor
,
remaining
//
divisor
])
todo
.
append
((
remaining
//
divisor
,
divisor
,
partial
+
[
divisor
]))
divisor
+=
1
return
combinations
def
recursive_get_factors
(
number
:
int
)
->
list
[
list
[
int
]]:
"""Return all factor combinations of number using recursion.
Args:
number: A positive integer.
Returns:
A list of lists, each containing a valid factorization.
Examples:
>>> recursive_get_factors(12)
[[2, 6], [2, 2, 3], [3, 4]]
"""
def
_factor
(
remaining
:
int
,
divisor
:
int
,
partial
:
list
[
int
],
combinations
:
list
[
list
[
int
]],
)
->
list
[
list
[
int
]]:
while
divisor
*
divisor
<=
remaining
:
if
remaining
%
divisor
==
0
:
combinations
.
append
(
partial
+
[
divisor
,
remaining
//
divisor
])
_factor
(
remaining
//
divisor
,
divisor
,
partial
+
[
divisor
],
combinations
)
divisor
+=
1
return
combinations
return
_factor
(
number
,
2
, [], [])
Back
|
FazBrowse Home
|
New Git URL