Add solution for problem 76 in C and python
This commit is contained in:
@ -68,7 +68,6 @@ def main():
|
||||
if l[i] == 1:
|
||||
count = count + 1
|
||||
|
||||
|
||||
end = default_timer()
|
||||
|
||||
print('Project Euler, Problem 75')
|
||||
|
24
Python/p076.py
Normal file
24
Python/p076.py
Normal file
@ -0,0 +1,24 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
from timeit import default_timer
|
||||
from projecteuler import partition_fn
|
||||
|
||||
def main():
|
||||
start = default_timer()
|
||||
|
||||
partitions = [0] * 101
|
||||
|
||||
# The number of ways a number can be written as a sum is given by the partition function
|
||||
# (-1 because the partition function includes also the number itself).
|
||||
# The function is implemented in projecteuler.py.
|
||||
n = partition_fn(100, partitions) - 1
|
||||
|
||||
end = default_timer()
|
||||
|
||||
print('Project Euler, Problem 76')
|
||||
print('Answer: {}'.format(n))
|
||||
|
||||
print('Elapsed time: {:.9f} seconds'.format(end - start))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
from math import sqrt, floor, gcd
|
||||
from math import sqrt, floor, ceil, gcd
|
||||
|
||||
from numpy import ndarray, zeros
|
||||
|
||||
@ -397,3 +397,33 @@ def phi(n, primes):
|
||||
ph = ph * (1 - 1 / n)
|
||||
|
||||
return ph
|
||||
|
||||
# Function implementing the partition function.
|
||||
def partition_fn(n, partitions):
|
||||
# The partition function for negative numbers is 0 by definition.
|
||||
if n < 0:
|
||||
return 0
|
||||
|
||||
# The partition function for zero is 1 by definition.
|
||||
if n == 0:
|
||||
partitions[n] = 1
|
||||
return 1
|
||||
|
||||
# If the partition for the current n has already been calculated, return the value.
|
||||
if partitions[n] != 0:
|
||||
return partitions[n]
|
||||
|
||||
res = 0
|
||||
k = -ceil((sqrt(24*n+1)-1)//6)
|
||||
limit = floor((sqrt(24*n+1)+1)//6)
|
||||
|
||||
while k <= limit:
|
||||
if k != 0:
|
||||
res = res + pow(-1, k+1) * partition_fn(n-k*(3*k-1)//2, partitions)
|
||||
k = k + 1
|
||||
|
||||
partitions[n] = res
|
||||
|
||||
return int(res)
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user