Skip to content

Commit

Permalink
Add for prime factors in python (#1940)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chalarangelo committed May 25, 2023
2 parents 20b7aba + be3514a commit 707b637
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions snippets/python/s/prime-factors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
title: Prime factors of number
type: snippet
language: python
tags: [math,algorithm]
cover: river-flow
dateModified: 2023-05-24T05:00:00+02:00
---

Finds and returns the list of prime factors of a number.

- Use a `while` loop to iterate over all possible prime factors, starting with `2`.
- If the current `factor` exactly divides `num`, add `factor` to the `factors` list and divide `num` by `factor`. Otherwise, increment `factor` by one.

```py
def prime_factors(num):
factors = []
factor = 2
while (num >= 2):
if (num % factor == 0):
factors.append(factor)
num = num / factor
else:
factor += 1
return factors
```

```py
prime_factors(12) # [2,2,3]
prime_factors(42) # [2,3,7]
```

0 comments on commit 707b637

Please sign in to comment.