factors of a number with memoization

Solutions on MaxInterview for factors of a number with memoization by the best coders in the world

showing results for - "factors of a number with memoization"
Estelle
10 Aug 2020
1import math
2
3def memoize(f):
4    memo = {}
5    def helper(x):
6        if x not in memo:
7            memo[x] = f(x)
8        return memo[x]
9    return helper
10
11@memoize
12def isprime (n):
13    if n == 1:
14        return False
15    elif n == 2:
16        return True
17    else:
18        for x in range (2, int(math.sqrt(n))+1):
19            if n % x == 0:
20                return False
21                break
22        else:
23            return True
24
25
26def factors (a):
27    if a == 1:
28        return []
29    elif isprime(a):
30        return [a]
31    else:
32        for x in range (2, int(math.sqrt(a))+1):
33            if a % x == 0:
34                return [x] + factors(a/x)
35
36testnumber = int(input("Enter a number."))
37print factors(testnumber)
38
similar questions
queries leading to this page
factors of a number with memoization