-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPrimes_in_numbers.py
60 lines (47 loc) · 1.4 KB
/
Primes_in_numbers.py
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
# Kata link:
# https://www.codewars.com/kata/54d512e62a5e54c96200019e
# -------------------------------------
# Instructions:
'''
Given a positive number n > 1 find the prime factor decomposition of n.
The result will be a string with the following form :
"(p1**n1)(p2**n2)...(pk**nk)"
where a ** b means a to the power of b
with the p(i) in increasing order and n(i) empty if n(i) is 1.
Example:
n = 86240 should return "(2**5)(5)(7**2)(11)"
'''
# -------------------------------------
# Solution:
def getAllPrimeFactors(n):
""" A simple trial division """
if (not isinstance(n, int)) or n <= 1:
if n == 1:
return [1]
else:
return []
else:
factors = []
prime = 2
while prime*prime <= n:
while (n % prime) == 0:
factors.append(prime)
n //= prime
prime += 1
if n > 1:
factors.append(n)
return factors
def primeFactors(n):
result = ""
factors = getAllPrimeFactors(n)
for i in sorted(set(factors)):
count = factors.count(i)
if count == 1:
result += "({})".format(i)
else:
result += "({}**{})".format(i, count)
return result
# -------------------------------------
# Basic Tests
print(primeFactors(86240) == "(2**5)(5)(7**2)(11)")
print(primeFactors(7775460) == "(2**2)(3**3)(5)(7)(11**2)(17)")