Project Euler 5 in Python - How can I optimize my solution? - python

I've recently been working on Project Euler problems in Python. I am fairly new to Python, and still somewhat new as a programmer.
In any case, I've ran into a speed-related issue coding a solution for problem #5. The problem is,
"2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
I've checked around some, and I haven't been able to find anything on this problem pertaining to Python specifically. There were some completed scripts, but I want to avoid looking at other's code in full, if possible, instead wanting to improve my own.
The code I have written runs successfully for the example of 2520 and the range 1 to 10, and should be directly modifiable to work with the question. However, upon running it, I do not get an answer. Presumably, it is a very high number, and the code is not fast enough. Printing the current number being checked seems to support this, reaching several million without getting an answer.
The code, in it's current implementation is as follows:
rangemax = 20
def div_check(n):
for i in xrange(11,rangemax+1):
if n % i == 0:
continue
else:
return False
return True
if __name__ == '__main__':
num = 2
while not div_check(num):
print num
num += 2
print num
I have already made a couple changes which I think should help the speed. For one, for a number to be divisible by all numbers 1 to 20, it must be even, as only even numbers are divisible by 2. Hence, I can increment by 2 instead of 1. Also, although I didn't think of it myself, I found someone point out that a number divisible by 11 to 20 is divisible by 1 to 10. (Haven't checked that one, but it seems reasonable)
The code still, however is not fast enough. What optimisations, either programmatic, or mathematics, can I make to make this code run faster?
Thanks in advance to any who can help.

Taking the advice of Michael Mior and poke, I wrote a solution. I tried to use a few tricks to make it fast.
Since we need a relatively short list of numbers tested, then we can pre-build the list of numbers rather than repeatedly calling xrange() or range().
Also, while it would work to just put the numbers [1, 2, 3, ..., 20] in the list, we can think a little bit, and pull numbers out:
Just take the 1 out. Every integer is evenly divisible by 1.
If we leave the 20 in, there is no need to leave the 2 in. Any integer evenly divisible by 20 is evenly divisible by 2 (but the reverse might not be true). So we leave the 20 and take out the 2, the 4, and the 5. Leave the 19, as it's prime. Leave the 18, but now we can take out the 3 and the 6. If you repeat this process, you wind up with a much shorter list of numbers to try.
We start at 20 and step numbers by 20, as Michael Mior suggested. We use a generator expression inside of all(), as poke suggested.
Instead of a while loop, I used a for loop with xrange(); I think this is slightly faster.
The result:
check_list = [11, 13, 14, 16, 17, 18, 19, 20]
def find_solution(step):
for num in xrange(step, 999999999, step):
if all(num % n == 0 for n in check_list):
return num
return None
if __name__ == '__main__':
solution = find_solution(20)
if solution is None:
print "No answer found"
else:
print "found an answer:", solution
On my computer, this finds an answer in under nine seconds.
EDIT:
And, if we take advice from David Zaslavsky, we realize we can start the loop at 2520, and step by 2520. If I do that, then on my computer I get the correct answer in about a tenth of a second.
I made find_solution() take an argument. Try calling find_solution(2520).

My first answer sped up the original calculation from the question.
Here's another answer that solves it a different way: just find all the prime factors of each number, then multiply them together to go straight to the answer. In other words, this automates the process recommended by poke in a comment.
It finishes in a fraction of a second. I don't think there is a faster way to do this.
I did a Google search on "find prime factors Python" and found this:
http://www.stealthcopter.com/blog/2009/11/python-factors-of-a-number/
From that I found a link to factor.py (written by Mike Hansen) with some useful functions:
https://gist.github.com/weakish/986782#file-factor-py
His functions didn't do quite what I wanted, so I wrote a new one but used his pull_prime_factors() to do the hard work. The result was find_prime_factors() which returns a list of tuples: a prime number, and a count. For example, find_prime_factors(400) returns [(2,4), (5,2)] because the prime factors of 400 are: (2*2*2*2)*(5*5)
Then I use a simple defaultdict() to keep track of how many we have seen so far of each prime factor.
Finally, a loop multiplies everything together.
from collections import defaultdict
from factor import pull_off_factors
pf = defaultdict(int)
_primes = [2,3,5,7,11,13,17,19,23,29]
def find_prime_factors(n):
lst = []
for p in _primes:
n = pull_off_factors(n, p, lst)
return lst
def find_solution(low, high):
for num in xrange(low, high+1):
lst = find_prime_factors(num)
for n, count in lst:
pf[n] = max(pf[n], count)
print "prime factors:", pf
solution = 1
for n, count in pf.items():
solution *= n**count
return solution
if __name__ == '__main__':
solution = find_solution(1, 20)
print "answer:", solution
EDIT: Oh wow, I just took a look at #J.F. Sebastian's answer to a related question. His answer does essentially the same thing as the above code, only far more simply and elegantly. And it is in fact faster than the above code.
Least common multiple for 3 or more numbers
I'll leave the above up, because I think the functions might have other uses in Project Euler. But here's the J.F. Sebastian solution:
def gcd(a, b):
"""Return greatest common divisor using Euclid's Algorithm."""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""Return lowest common multiple."""
return a * b // gcd(a, b)
def lcmm(*args):
"""Return lcm of args."""
return reduce(lcm, args)
def lcm_seq(seq):
"""Return lcm of sequence."""
return reduce(lcm, seq)
solution = lcm_seq(xrange(1,21))
print "lcm_seq():", solution
I added lcm_seq() but you could also call:
lcmm(*range(1, 21))

Since your answer must be divisible by 20, you can start at 20 and increment by 20 instead of by two. In general, you can start at rangemax and increment by rangemax. This reduces the number of times div_check is called by an order of magnitude.

Break down the number as a prime factorization.
All primes less than 20 are:
2,3,5,7,11,13,17,19
So the bare minimum number that can be divided by these numbers is:
2*3*5*7*11*13*17*19
Composites:
4,6,8,9,10,12,14,15,16,18,20 = 2^2, 2*3, 2^3, 3^2, 2*5, 2^2*3, 2*7, 3*5, 2*3^2, 2^2*5
Starting from the left to see which factors needed:
2^3 to build 4, 8, and 16
3 to build 9
Prime factorization: 2^4 * 3^2 * 5 * 7 * 11 * 13 * 17 * 19 = 232,792,560

I got the solution in 0.066 milliseconds (only 74 spins through a loop) using the following procedure:
Start with smallest multiple for 1, which = 1. Then find the smallest multiple for the next_number_up. Do this by adding the previous smallest multiple to itself (smallest_multiple = smallest_multiple + prev_prod) until next_number_up % smallest_multiple == 0. At this point smallest_multiple is the correct smallest multiple for next_number_up. Then increment next_number_up and repeat until you reach the desired smallest_multiple (in this case 20 times). I believe this finds the solution in roughly n*log(n) time (though, given the way numbers seem to work, it seems to complete much faster than that usually).
For example:
1 is the smallest multiple for 1
Find smallest multiple for 2
Check if previous smallest multiple works 1/2 = .5, so no
previous smallest multiple + previous smallest multiple == 2.
Check if 2 is divisible by 2 - yes, so 2 is the smallest multiple for 2
Find smallest multiple for 3
Check if previous smallest multiple works 2/3 = .667, so no
previous smallest multiple + previous smallest multiple == 4
Check if 4 is divisible by 3 - no
4 + previous smallest multiple == 6
Check if 6 is divisible by 3 - yes, so 6 is the smallest multiple for 3
Find smallest multiple for 4
Check if previous smallest multiple works 6/4 = 1.5, so no
previous smallest multiple + previous smallest multiple == 12
Check if 12 is divisble by 4 - yes, so 12 is the smallest multiple for 4
repeat until 20..
Below is code in ruby implementing this approach:
def smallestMultiple(top)
prod = 1
counter = 0
top.times do
counter += 1
prevprod = prod
while prod % counter != 0
prod = prod + prevprod
end
end
return prod
end

List comprehensions are faster than for loops.
Do something like this to check a number:
def get_divs(n):
divs = [x for x in range(1,20) if n % x == 0]
return divs
You can then check the length of the divs array to see if all the numbers are present.

Two different types of solutions have been posted here. One type uses gcd calculations; the other uses prime factorization. I'll propose a third type, which is based on the prime factorization approach, but is likely to be much faster than prime factorization itself. It relies on a few simple observations about prime powers -- prime numbers raised to some integral exponent. In short, it turns out that the least common multiple of all numbers below some number n is equal to the product of all maximal prime powers below n.
To prove this, we begin by thinking about the properties that x, the least common multiple of all numbers below n, must have, and expressing them in terms of prime powers.
x must be a multiple of all prime powers below n. This is obvious; say n = 20. 2, 2 * 2, 2 * 2 * 2, and 2 * 2 * 2 * 2 are all below 20, so they all must divide x. Likewise, 3 and 3 * 3 are both below n and so both must divide x.
If some number a is a multiple of the prime power p ** e, and p ** e is the maximal power of p below n, then a is also a multiple of all smaller prime powers of p. This is also quite obvious; if a == p * p * p, then a == (p * p) * p.
By the unique factorization theorem, any number m can be expressed as a multiple of prime powers less than m. If m is less than n, then m can be expressed as a multiple of prime powers less than n.
Taken together, the second two observations show that any number x that is a multiple of all maximal prime powers below n must be a common multiple of all numbers below n. By (2), if x is a multiple of all maximal prime powers below n, it is also a multiple of all prime powers below n. So by (3), it is also a multiple of all other numbers below n, since they can all be expressed as multiples of prime powers below n.
Finally, given (1), we can prove that x is also the least common multiple of all numbers below n, because any number less than x could not be a multiple of all maximal prime powers below n, and so could not satisfy (1).
The upshot of all this is that we don't need to factorize anything. We can just generate primes less than n!
Given a nicely optimized sieve of eratosthenes, one can do that very quickly for n below one million. Then all you have to do is find the maximal prime power below n for each prime, and multiply them together.
prime_powers = [get_max_prime_power(p, n) for p in sieve(n)]
result = reduce(operator.mul, prime_powers)
I'll leave writing get_max_prime_power as an exercise. A fast version, combined with the above, can generate the lcm of all numbers below 200000 in 3 seconds on my machine.
The result is a 86871-digit number!

This solution ran pretty quickly for me (imports numpy).
t0 = time.time()
import numpy
ints = numpy.array(range(1,21))
primes = [2,3,5,7,11,13,17,19] # under 20
facts = []
for p in primes:
counter = 0
nums = ints
while any(nums % p == 0):
nums = nums / float(p)
counter += 1
facts.append(counter)
facts = numpy.array(facts)
mults = primes**facts
ans = 1
for m in mults:
ans = m * ans
t1 =time.time()
perf = t1 - t0
print "Problem 5\nAnswer:",ans, "runtime:", perf, "seconds"
"""Problem 5
Answer: 232792560 runtime: 0.00505399703979 seconds"""

Here i have also done using prime factorization way.
#!/usr/bin/env python
import math
def is_prime(num):
if num > 1:
if num == 2:
return True
if num%2 == 0:
return False
for i in range(3, int(math.sqrt(num))+1, 2):
if num%i == 0:
return False
return True
return False
def lcm(number):
prime = []
lcm_value = 1
for i in range(2,number+1):
if is_prime(i):
prime.append(i)
final_value = []
for i in prime:
x = 1
while i**x < number:
x = x + 1
final_value.append(i**(x-1))
for j in final_value:
lcm_value = j * lcm_value
return lcm_value
if __name__ == '__main__':
print lcm(20)
After checking how much time it has taken, it was not bad at all.
root#l-g6z6152:~/learn/project_euler# time python lcm.py
232792560
real 0m0.019s
user 0m0.008s
sys 0m0.004s

I wrote a solution to euler5 that:
Is orders of magnitude faster than most of the solutions here when n=20 (though not all respondents report their time) because it uses no imports (other than to measure time for this answer) and only basic data structures in python.
Scales much better than most other solutions. It will give the answer for n=20 in 6e-05 seconds, or for n=100 in 1 millisec, faster than most of the responses for n=20 listed here.
import time
a=time.clock() # set timer
j=1
factorlist=[]
mydict={}
# change second number to desired number +1 if the question were changed.
for i in range(2,21,1):
numberfactors=[]
num=i
j=2
# build a list of the prime factors
for j in range(j,num+1,1):
counter=0
if i%j==0:
while i%j==0:
counter+=1
numberfactors.append(j)
i=i/j
# add a list of factors to a dictionary, with each prime factor as a key
if j not in mydict:
mydict[j] = counter
# now, if a factor is already present n times, including n times the factor
# won't increase the LCM. So replace the dictionary key with the max number of
# unique factors if and only if the number of times it appears is greater than
# the number of times it has already appeared.
# for example, the prime factors of 8 are 2,2, and 2. This would be replaced
# in the dictionary once 16 were found (prime factors 2,2,2, and 2).
elif mydict[j] < counter:
mydict[j]=counter
total=1
for key, value in mydict.iteritems():
key=int(key)
value=int(value)
total=total*(key**value)
b=time.clock()
elapsed_time=b-a
print total, "calculated in", elapsed_time, "seconds"
returns:
232792560 calculated in 6e-05 seconds
# does not rely on heuristics unknown to all users, for instance the idea that
# we only need to include numbers above 10, etc.
# For all numbers evenly divisible by 1 through 100:
69720375229712477164533808935312303556800 calculated in 0.001335 seconds

Here is program in C language. Cheers
#include <stdio.h>
#include <stdlib.h>
//2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
//What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
bez_ost(int q)
{
register br=0;
for( register i=1;i<=20;i++)
if(q%i==0)
br++;
if(br==20)
return 1;
return 0;
}
int main()
{
register j=20;
register ind=0;
while(ind!=1)
{
j++;
if(bez_ost(j))
break;
}
fprintf(stdout,"\nSmallest positive number that is evenlu divisible by all of the numbers from 1 to 20 is: %d\n\a",j);
system("Pause");
}

I've had the same problem. The algorithm seems to be quite slow, but it does work nonetheless.
result = list()
xyz = [x for x in range(11, 21)]
number = [2520]
count = 0
while len(result) == 0:
for n in number:
print n
for x in xyz:
if n % x == 0:
count += 1
elif n % x != 0:
count = 0
break
if count == 10:
result.append(number[0])
elif count != 10:
number[0] += 1
print result
This was the algorithm I made.

How about this? The required number is, after all, the LCM of the given numbers.
def lcm(a,b):
lcm1 = 0
if a == b:
lcm1 = a
else:
if a > b:
greater = a
else:
greater = b
while True:
if greater % a == 0 and greater % b == 0:
lcm1 = greater
break
greater += 1
return lcm1
import time
start_time = time.time()
list_numbers = list(range(2,21))
lcm1 = lcm(list_numbers[0],list_numbers[1])
for i in range(2,len(list_numbers)):
lcm1 = lcm(lcm1,list_numbers[i])
print(lcm1)
print('%0.5f'%(time.time()-start_time))
This code took a full 45 s to get the answer to the actual question! Hope it helps.

import time
primes = [11,13,17,19]
composites = [12,14,15,16,18,20]
def evenlyDivisible(target):
evenly = True
for n in composites:
if target % n > 0:
evenly = False
break
return evenly
step = 1
for p in primes:
step *= p
end = False
number = 0
t1 = time.time()
while not end:
number += step
if evenlyDivisible(number):
end = True
print("Smallest positive evenly divisible number is",number)
t2 = time.time()
print("Time taken =",t2-t1)
Executed in 0.06 seconds

Here is my Python solution, it has 12 iteration so compiled quite fast:
smallest_num = 1
for i in range (1,21):
if smallest_num % i > 0: # If the number is not divisible by i
for k in range (1,21):
if (smallest_num * k) % i == 0: # Find the smallest number divisible by i
smallest_num = smallest_num * k
break
print (smallest_num)

Here's an observation on this problem. Ultimately, it takes 48 iterations to find the solution.
Any number that is divisible by all of the numbers from 1..20 must be divisible by the product of the primes in that range, namely 2, 3, 5, 7, 11, 13, 17, and 19. It cannot be smaller than the product of these primes, so let's use that number, 232,792,560, as the increment, rather than 20, or 2,520, or some other number.
As it turns out, 48 * 232,792,560 is divisible by all numbers 1..20. By the way, the product of all of the non-primes between 1..20 is 66. I haven't quite figured out the relationship between 48 and 66 in this context.

up = int(input('Upper limit: '))
number = list(range(1, up + 1))
n = 1
for i in range(1, up):
n = n * number[i]
for j in range(i):
if number[i] % number[j] == 0:
n = n / number[j]
number[i] = number[i] / number[j]
print(n)

How I can reduce the complexity of this
num = 1
found = False
while not found:
count =0
for i in range(1, 21):
if num %i == 0:
count+=1
if count ==10:
print(num)
found = True
num+=1

Here is the code in C++ to find the solution for this question.
What we have to do is to run a loop from 1 until we got that number so just iterate through the loop and once the number get evenly divisble(remainder 0) flag value dont get change and flag remains 1 and we got that number and break through outer loop and print the answer
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int i,j,flag=1;
for(i=1;;i++) //iterate until we got the number
{
flag=1;
for(j=2;j<=20;j++) //check form 1 to 20 for that number
{
if(i%j!=0) //if the number is not evenly divisible we break loop and
{
flag=0;break; // initilize flag as 0 i.e. that number is not what we want
}
}
if(flag==1) //if any number we got that is evenly divisible i.e. flag value doesnt change we got that number we break through the loop and print the answer
break;
} // after ending of the loop as we jump to next number make flag also 1 again so that again inner loop conditions apply on it
cout<<i;
return 0;
}

A typescript variant that seems to be relatively quick, leveraging recursion and known facts.
describe(`2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?`,
() => {
it("prooves the example: 10", () => smallestWithoutRemainder(10).should.be.equal(2520));
it("prooves 1", () => smallestWithoutRemainder(1).should.be.equal(1));
it("prooves 2", () => smallestWithoutRemainder(2).should.be.equal(2));
it("prooves 3", () => smallestWithoutRemainder(3).should.be.equal(6));
it("prooves 4", () => smallestWithoutRemainder(4).should.be.equal(12));
it("prooves 5", () => smallestWithoutRemainder(5).should.be.equal(60));
it("prooves 6", () => smallestWithoutRemainder(6).should.be.equal(60));
it("prooves 7", () => smallestWithoutRemainder(7).should.be.equal(420));
it("prooves 8", () => smallestWithoutRemainder(8).should.be.equal(840));
it("prooves 9", () => smallestWithoutRemainder(9).should.be.equal(2520));
it("prooves 12", () => smallestWithoutRemainder(12).should.be.equal(27720));
it("prooves 20", () => smallestWithoutRemainder(20).should.be.equal(232792560));
it("prooves 30", () => smallestWithoutRemainder(30).should.be.equal(2329089562800));
it("prooves 40", () => smallestWithoutRemainder(40).should.be.equal(5342931457063200));
});
let smallestWithoutRemainder = (end: number, interval?: number) => {
// What do we know?
// - at 10, the answer is 2520
// - can't be smaller than the lower multiple of 10
// - must be an interval of the lower multiple of 10
// so:
// - the interval and the start should at least be divisable by 'end'
// - we can recurse and build on the results before it.
if (!interval) interval = end;
let count = Math.floor(end / 10);
if (count == 1) interval = 2520;
else if (count > 1) interval = smallestWithoutRemainder((count - 1) * 10, interval);
for (let i = interval; true; i += interval) {
let failed = false;
for (let j = end; j > 1; j--) {
if (i % j != 0) {
failed = true;
break;
}
}
if (!failed) return i;
}
}

I think this the answer:
primes = [11, 13, 17, 19]
result = 2520
for i in primes:
result *= i
print (result * 2)

Related

Prime checker including non primes

I am trying to solve Project Euler number 7.
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
First thing that came into my mind was using length of list. This was very ineffective solution as it took over a minute. This is the used code.
def ch7():
primes = []
x = 2
while len(primes) != 10001:
for i in range(2, x):
if x % i == 0:
break
else:
primes.append(x)
x += 1
print(primes[-1])
ch7()
# Output is: 104743.
This works well but I wanted to reach faster solution. Therefore I did a bit of research and found out that in order to know if a number is a prime, we need to test whether it is divisible by any number up to its square root e.g. in order to know if 100 is a prime we dont need to divide it by every number up to 100, but only up to 10.
When I implemented this finding weird thing happened. The algorithm included some non primes. To be exact 66 of them. This is the adjusted code:
import math
primes = []
def ch7():
x = 2
while len(primes) != 10001:
for i in range(2, math.ceil(math.sqrt(x))):
if x % i == 0:
break
else:
primes.append(x)
x += 1
print(primes[-1])
ch7()
# Output is 104009
This solution takes under a second but it includes some non primes. I used math.ceil() in order to get int instead of float but I figured it should not be a problem since it still tests by every int up to square root of x.
Thank you for any suggestions.
Your solution generates a list of primes, but doens't use that list for anything but extracting the last element. We can toss that list, and cut the time of the code in half by treating 2 as a special case, and only testing odd numbers:
def ch7(limit=10001): # assume limit is >= 1
prime = 2
number = 3
count = 1
while count < limit:
for divisor in range(3, int(number ** 0.5) + 1, 2):
if number % divisor == 0:
break
else: # no break
prime = number
count += 1
number += 2
return prime
print(ch7())
But if you're going to collect a list of primes, you can use that list to get even more speed out of the program (about 10% for the test limits in use) by using those primes as divisors instead of odd numbers:
def ch7(limit=10001): # assume limit is >= 1
primes = [2]
number = 3
while len(primes) < limit:
for prime in primes:
if prime * prime > number: # look no further
primes.append(number)
break
if number % prime == 0: # composite
break
else: # may never be needed but prime gaps can be arbitrarily large
primes.append(number)
number += 2
return primes[-1]
print(ch7())
BTW, your second solution, even with the + 1 fix you mention in the comments, comes up with one prime beyond the correct answer. This is due to the way your code (mis)handles the prime 2.

How to find even sum

I need to find the sum of all even numbers below the inserted number. For example if I insert 8 then the sum would be 2+4+6+8=20. If I insert 9 then it also needs to be 20. And it needs to be based on recursion.
This is what I have so far:
def even(a):
if a == 0:
else:
even(a - 1)
even(8)
I cannot figure out what to change under the "if" part for it to give the right outcome
If the function is called with an odd number, n, then you can immediately call again with the number below (an even).
Then if the function is called with an even number return that even number plus the result of summing all the even numbers below this number by calling again with n - 2.
Finally, your base case occurs when n = 0. In this case just return 0.
So we have
def even_sum(n):
if n % 2 == 1: # n is odd
return even_sum(n - 1)
if n == 0:
return 0
return n + even_sum(n - 2)
which works as expected
>>> even_sum(8)
20
>>> even_sum(9)
20
>>> even_sum(0)
0
To design a recursive algorithm, the first thing to wonder is "In what cases can my algorithm return an answer trivially?". In your case, the answer is "If it is called with 0, the algorithm answers 0". Hence, you can write:
def even(n):
if n == 0:
return 0
Now the next question is "Given a particular input, how can I reduce the size of this input, so that it will eventually reach the trivial condition?"
If you have an even number, you want to have this even number + the sum of even numbers below it, which is the result of even(n-2). If you have an odd number, you want to return the sum of even numbers below it. Hence the final version of your function is:
def even(n):
if n == 0 or n == 1:
return 0
if n % 2 == 0:
return n + even(n - 2)
return even(n - 1)
Both with o(n) time complexity
With For loop
num = int(input("Enter a number: ")) # given number to find sum
my_sum = 0
for n in range(num + 1):
if n % 2 == 0:
my_sum += n
print(my_sum)
With recursion
def my_sum(num):
if num == 0:
return 0
if num % 2 == 1:
return my_sum(num - 1)
return num + my_sum(num - 2)
always avoid O(n^2) and greater time complexity
For a recursive solution:
def evenSum(N): return 0 if N < 2 else N - N%2 + evenSum(N-2)
If you were always given an even number as input, you could simply recurse using N + f(N-2).
For example: 8 + ( 6 + (4 + ( 2 + 0 ) ) )
But the odd numbers will require that you strip the odd bit in the calculation (e.g. subtracting 1 at each recursion)
For example: 9-1 + ( 7-1 + ( 5-1 + ( 3-1 + 0 ) ) )
You can achieve this stripping of odd bits by subtracting the modulo 2 of the input value. This subtracts zero for even numbers and one for odd numbers.
adjusting your code
Your approach is recursing by 1, so it will go through both the even and odd numbers down to zero (at which point it must stop recursing and simply return zero).
Here's how you can adjust it:
Return a value of zero when you are given zero as input
Make sure to return the computed value that comes from the next level of recursion (you are missing return in front of your call to even(a-1)
Add the parameter value when it is even but don't add it when it is odd
...
def even(a):
if a == 0 : return 0 # base case, no further recusion
if a%2 == 1 : return even(a-1) # odd number: skip to even number
return a + even(a-1) # even number: add with recursion
# a+even(a-2) would be better
A trick to create a recursive function
An easy way to come up with the structure of a recursive function is to be very optimistic and imagine that you already have one that works. Then determine how you would use the result of that imaginary function to produce the next result. That will be the recursive part of the function.
Finally, find a case where you would know the answer without using the function. That will be your exit condition.
In this case (sum of even numbers), imagine you already have a function magic(x) that gives you the answer for x. How would you use it to find a solution for n given the result of magic(n-1) ?
If n is even, add it to magic(n-1). If n is odd, use magic(n-1) directly.
Now, to find a smaller n where we know the answer without using magic(). Well if n is less than 2 (or zero) we know that magic(n) will return zero so we can give that result without calling it.
So our recursion is "n+magic(n-1) if n is even, else magic(n-1)"
and our stop condition is "zero if n < 2"
Now substitute magic with the name of your function and the magic is done.
For an O(1) solution:
Given that the sum of numbers from 1 to N can be calculated with N*(N+1)//2, you can get half of the sum of even numbers if you use N//2 in the formula. Then multiply the result by 2 to obtain the sum of even numbers.
so (N//2)*(N//2+1) will give the answer directly in O(1) time:
N = 8
print((N//2)*(N//2+1))
# 20
# other examples:
for N in range(10):
print(N,N//2*(N//2+1))
# 0 0
# 1 0
# 2 2
# 3 2
# 4 6
# 5 6
# 6 12
# 7 12
# 8 20
# 9 20
Visually, you can see the progression like this:
1..n : 1 2 3 4 5 6 7 8
∑n : 1 3 6 10 15 21 28 36 n(n+1)/2
n/2 : 0 1 1 2 2 3 3 4
1..n/2 : 1 2 3 4
∑n/2 : 1 3 5 10 half of the result
2∑n/2 : 2 6 10 20 sum of even numbers
So we simply replace N with N//2 in the formula and multiply the result by 2:
N*(N+1)//2 --> replace N with N//2 --> N//2*(N//2+1)//2
N//2*(N//2+1)//2 --> multiply by 2 --> N//2*(N//2+1)
Another way to see it is using Gauss's visualisation of the sum of numbers but using even numbers:
ascending 2 4 6 8 ... N-6 N-4 N-2 N (where N is even)
descending N N-2 N-4 N-6 ... 8 6 4 2
--- --- --- --- --- --- --- ---
totals N+2 N+2 N+2 N+2 ... N+2 N+2 N+2 N+2 (N/2 times N+2)
Because we added the even numbers twice, once in ascending order and once in descending order, the sum of all the totals will be twice the sum of even numbers (we need to divide that sum by 2 to get what we are looking for).
sum of evens: N/2*(N+2)/2 --> N/2*(N/2+1)
The N/2(N/2+1) formulation allows us to supply the formula with an odd number and get the right result by using integer division which absorbs the 'odd bit': N//2(N//2+1)
Recursive O(1) solution
Instead of using the integer division to absorb the odd bit, you could use recursion with the polynomial form of N/2*(N+2)/2: N^2/4 + N/2
def sumEven(n):
if n%2 == 0 : return n**2/4 + n/2 # exit condition
return sumEven(n-1) # recursion
Technically this is recursive although in practice it will never go deeper than 1 level
Try out this.
>>> n = 5
>>> sum(range(0, n+1, 2))
with minimum complexity
# include <stdio.h>
void main()
{
int num, sum, i;
printf("Number: ");
scanf("%d", &num);
i = num;
if (num % 2 != 0)
num = num -1;
sum = (num * (num + 2)) / 4;
printf("The sum of even numbers upto %d is %d\n\n", i, sum);
}
It is a C program and could be used in any language with respective syntax.
And it needs to be based on recursion.
Though you want a recursion one, I still want to share this dp solution with detailed steps to solve this problem.
Dynamic Programming
dp[i] represents the even sum among [0, i] which I denote as nums.
Case1: When i is 0, there is one number 0 in nums. dp[0] is 0.
Case2: When i is 1, there are two numbers 0 and 1 in nums. dp[1] is still 0.
Case3: When i is 2, there are three numbers 0, 1 and 2 in nums. dp[2] is 2.
Case4: When i is greater than 2, there are two more cases
If i is odd, dp[i] = dp[i-1]. Since i is odd, it is the same with [0, i-1].
If i is even, dp[i] = dp[i-2] + i by adding the current even number to the even sum among [0, i-2] (i-1 is odd, so won't be added).
PS. dp[i] = dp[i-1] + i is also ok. The difference is how you initialize dp.
Since we want the even sum among [0, n], we return dp[n]. You can conclude this from the first three cases.
def even_sum(n):
dp = []
# Init
dp.append(0) # dp[0] = 0
dp.append(0) # dp[1] = 0
# DP
for i in range(2, n+1): # n+1 because range(i, j) results [i, j) and you take n into account
if i % 2 == 1: # n is odd
dp.append(dp[i-1]) # dp[i] = dp[i-1]
else: # n is even
dp.append(dp[i-2] + i) # dp[i] = dp[i-2] + i
return dp[-1]

Finding the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? [duplicate]

This question already has answers here:
Least common multiple for 3 or more numbers
(32 answers)
Closed 5 years ago.
This is a Project Euler challenge where I'm trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
The logic while I came up with seems to run really slowly. It's been running for the last 4 mins and still hasn't found the number. I'm trying to figure out a) Is this logic correct? b) Why does this take so long? and c) Could someone give me a hint on an alternate logic that is more efficient.
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
smallest_num = 2520
while smallest_num >= 2520:
divisor = 2
while smallest_num % divisor == 0 and divisor < 21:
print("Smalles num = {} and Divisor = {}").format(smallest_num, divisor)
divisor += 1
smallest_num += 1
print("Smallest number is: {}").format(smallest_num)
This is still processing and so far my terminal looks like this
Here's your method run "properly" (using the term liberally), but as #James mentioned it will take an egregious amount of time as a loop.
divisors = np.arange(1, 21)
num = 2520
while True:
if np.all(num % divisors == 0):
print(num)
break
num += 1
A much better method (for Python 3.x). Directly from a similar question:
import functools
import math
functools.reduce(lambda x,y: x*y//math.gcd(x, y), range(1, 21))
Out[27]: 232792560
The following code works fine.
#!/usr/bin/env python
import math
#Generating primes
divisorMax = 20;
top = divisorMax + 1 #divisor max is the upper limit
p = [x for x in range(2,top)]
for num in p:
for idx in range(2,(top//num)+1):
if num*idx in p:
p.remove(num*idx)
#Solving the problem
result = 1;
for i in range(0, len(p)):
a = math.floor(math.log(divisorMax) / math.log(p[i]));
result = result * (p[i]**a);
print(result)
You are using brute force technique to calculate the number, which is easy to understand and write, but takes very much time.
I am using the Prime Factorisation technique explained here.
i am not 100% sure, if my solution is really correct, but i guess it is and it is pretty fast.
First of all, we don't need to care for all divisors, as most are multiples of each other. So best way is to count the divisors backwards, for example starting with 20 down to 1.
I had a look at the prime numbers, the solution needs to be a multiple of all primes above 10, furthermore we need to check the 20 divisor, the rest can be ignored, as when testing divisor 18, the 9 will work as well, and so on.
So i mulitplied 11 * 13 * 17 * 19 * 20. The resulting is 923780 and is divisible by at least the primes + 20.
So i would start at 923780 and test only every 923780th number.
smallest_num = 923780
steps = 923780
while True:
divisor = 19
while smallest_num % divisor == 0 and divisor > 10:
print("Smalles num = {} and Divisor = {}").format(smallest_num, divisor)
divisor -= 1
if divisor == 10:
print("Smallest number is: {}").format(smallest_num)
break
smallest_num += steps
Maybe i have logical error?!

efficient ways of finding the largest prime factor of a number

I'm doing this problem on a site that I found (project Euler), and there is a question that involves finding the largest prime factor of a number. My solution fails at really large numbers so I was wondering how this code could be streamlined?
""" Find the largest prime of a number """
def get_factors(number):
factors = []
for integer in range(1, number + 1):
if number%integer == 0:
factors.append(integer)
return factors
def test_prime(number):
prime = True
for i in range(1, number + 1):
if i!=1 and i!=2 and i!=number:
if number%i == 0:
prime = False
return prime
def test_for_primes(lst):
primes = []
for i in lst:
if test_prime(i):
primes.append(i)
return primes
################################################### program starts here
def find_largest_prime_factor(i):
factors = get_factors(i)
prime_factors = test_for_primes(factors)
print prime_factors
print find_largest_prime_factor(22)
#this jams my computer
print find_largest_prime_factor(600851475143)
it fails when using large numbers, which is the point of the question I guess. (computer jams, tells me I have run out of memory and asks me which programs I would like to stop).
************************************ thanks for the answer. there was actually a couple bugs in the code in any case. so the fixed version of this (inefficient code) is below.
""" Find the largest prime of a number """
def get_factors(number):
factors = []
for integer in xrange(1, number + 1):
if number%integer == 0:
factors.append(integer)
return factors
def test_prime(number):
prime = True
if number == 1 or number == 2:
return prime
else:
for i in xrange(2, number):
if number%i == 0:
prime = False
return prime
def test_for_primes(lst):
primes = []
for i in lst:
if test_prime(i):
primes.append(i)
return primes
################################################### program starts here
def find_largest_prime_factor(i):
factors = get_factors(i)
print factors
prime_factors = test_for_primes(factors)
return prime_factors
print find_largest_prime_factor(x)
From your approach you are first generating all divisors of a number n in O(n) then you test which of these divisors is prime in another O(n) number of calls of test_prime (which is exponential anyway).
A better approach is to observe that once you found out a divisor of a number you can repeatedly divide by it to get rid of all of it's factors. Thus, to get the prime factors of, say 830297 you test all small primes (cached) and for each one which divides your number you keep dividing:
830297 is divisible by 13 so now you'll test with 830297 / 13 = 63869
63869 is still divisible by 13, you are at 4913
4913 doesn't divide by 13, next prime is 17 which divides 4913 to get 289
289 is still a multiple of 17, you have 17 which is the divisor and stop.
For further speed increase, after testing the cached prime numbers below say 100, you'll have to test for prime divisors using your test_prime function (updated according to #Ben's answer) but go on reverse, starting from sqrt. Your number is divisible by 71, the next number will give an sqrt of 91992 which is somewhat close to 6857 which is the largest prime factor.
Here is my favorite simple factoring program for Python:
def factors(n):
wheel = [1,2,2,4,2,4,2,4,6,2,6]
w, f, fs = 0, 2, []
while f*f <= n:
while n % f == 0:
fs.append(f)
n /= f
f, w = f + wheel[w], w+1
if w == 11: w = 3
if n > 1: fs.append(n)
return fs
The basic algorithm is trial division, using a prime wheel to generate the trial factors. It's not quite as fast as trial division by primes, but there's no need to calculate or store the prime numbers, so it's very convenient.
If you're interested in programming with prime numbers, you might enjoy this essay at my blog.
My solution is in C#. I bet you can translate it into python. I've been test it with random long integer ranging from 1 to 1.000.000.000 and it's doing good. You can try to test the result with online prime calculator Happy coding :)
public static long biggestPrimeFactor(long num) {
for (int div = 2; div < num; div++) {
if (num % div == 0) {
num \= div
div--;
}
}
return num;
}
The naive primality test can be improved upon in several ways:
Test for divisibility by 2 separately, then start your loop at 3 and go by 2's
End your loop at ceil(sqrt(num)). You're guaranteed to not find a prime factor above this number
Generate primes using a sieve beforehand, and only move onto the naive way if you've exhausted the numbers in your sieve.
Beyond these easy fixes, you're going to have to look up more efficient factorization algorithms.
Use a Sieve of Eratosthenes to calculate your primes.
from math import sqrt
def sieveOfEratosthenes(n):
primes = range(3, n + 1, 2) # primes above 2 must be odd so start at three and increase by 2
for base in xrange(len(primes)):
if primes[base] is None:
continue
if primes[base] >= sqrt(n): # stop at sqrt of n
break
for i in xrange(base + (base + 1) * primes[base], len(primes), primes[base]):
primes[i] = None
primes.insert(0,2)
return filter(None, primes)
The point to prime factorization by trial division is, the most efficient solution for factorizing just one number doesn't need any prime testing.
You just enumerate your possible factors in ascending order, and keep dividing them out of the number in question - all thus found factors are guaranteed to be prime. Stop when the square of current factor exceeds the current number being factorized. See the code in user448810's answer.
Normally, prime factorization by trial division is faster on primes than on all numbers (or odds etc.), but when factorizing just one number, to find the primes first to test divide by them later, will might cost more than just going ahead with the increasing stream of possible factors. This enumeration is O(n), prime generation is O(n log log n), with the Sieve of Eratosthenes (SoE), where n = sqrt(N) for the top limit N. With trial division (TD) the complexity is O(n1.5/(log n)2).
Of course the asymptotics are to be taken just as a guide, actual code's constant factors might change the picture. Example, execution times for a Haskell code derived from here and here, factorizing 600851475149 (a prime):
2.. 0.57 sec
2,3,5,... 0.28 sec
2,3,5,7,11,13,17,19,... 0.21 sec
primes, segmented TD 0.65 sec first try
0.05 sec subsequent runs (primes are memoized)
primes, list-based SoE 0.44 sec first try
0.05 sec subsequent runs (primes are memoized)
primes, array-based SoE 0.15 sec first try
0.06 sec subsequent runs (primes are memoized)
so it depends. Of course factorizing the composite number in question, 600851475143, is near instantaneous, so it doesn't matter there.
Here is an example in JavaScript
function largestPrimeFactor(val, divisor = 2) {
let square = (val) => Math.pow(val, 2);
while ((val % divisor) != 0 && square(divisor) <= val) {
divisor++;
}
return square(divisor) <= val
? largestPrimeFactor(val / divisor, divisor)
: val;
}
I converted the solution from #under5hell to Python (2.7x). what an efficient way!
def largest_prime_factor(num, div=2):
while div < num:
if num % div == 0 and num/div > 1:
num = num /div
div = 2
else:
div = div + 1
return num
>> print largest_prime_factor(600851475143)
6857
>> print largest_prime_factor(13195)
29
Try this piece of code:
from math import *
def largestprime(n):
i=2
while (n>1):
if (n % i == 0):
n = n/i
else:
i=i+1
print i
strinput = raw_input('Enter the number to be factorized : ')
a = int(strinput)
largestprime(a)
Old one but might help
def isprime(num):
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
return False
return True
def largest_prime_factor(bignumber):
prime = 2
while bignumber != 1:
if bignumber % prime == 0:
bignumber = bignumber / prime
else:
prime = prime + 1
while isprime(prime) == False:
prime = prime+1
return prime
number = 600851475143
print largest_prime_factor(number)
I Hope this would help and easy to understand.
A = int(input("Enter the number to find the largest prime factor:"))
B = 2
while (B <(A/2)):
if A%B != 0:
B = B+1
else:
A = A/B
C = B
B = 2
print (A)
This code for getting the largest prime factor, with nums value of prime_factor(13195) when I run it, will return the result in less than a second.
but when nums value gets up to 6digits it will return the result in 8seconds.
Any one has an idea of what is the best algorithm for the solution...
def prime_factor(nums):
if nums < 2:
return 0
primes = [2]
x = 3
while x <= nums:
for i in primes:
if x%i==0:
x += 2
break
else:
primes.append(x)
x += 2
largest_prime = primes[::-1]
# ^^^ code above to gets all prime numbers
intermediate_tag = []
factor = []
# this code divide nums by the largest prime no. and return if the
# result is an integer then append to primefactor.
for i in largest_prime:
x = nums/i
if x.is_integer():
intermediate_tag.append(x)
# this code gets the prime factors [29.0, 13.0, 7.0, 5.0]
for i in intermediate_tag:
y = nums/i
factor.append(y)
print(intermediate_tag)
print(f"prime factor of {nums}:==>",factor)
prime_factor(13195)
[455.0, 1015.0, 1885.0, 2639.0]
prime factor of 13195:==> [29.0, 13.0, 7.0, 5.0]

Stuck on Project Euler #3 in python

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest
prime factor of the number 600851475143 ?
Ok, so i am working on project euler problem 3 in python. I am kind of confused. I can't tell if the answers that i am getting with this program are correct or not. If somone could please tell me what im doing wrong it would be great!
#import pdb
odd_list=[]
prime_list=[2] #Begin with zero so that we can pop later without errors.
#Define a function that finds all the odd numbers in the range of a number
def oddNumbers(x):
x+=1 #add one to the number because range does not include it
for i in range(x):
if i%2!=0: #If it cannot be evenly divided by two it is eliminated
odd_list.append(i) #Add it too the list
return odd_list
def findPrimes(number_to_test, list_of_odd_numbers_in_tested_number): # Pass in the prime number to test
for i in list_of_odd_numbers_in_tested_number:
if number_to_test % i==0:
prime_list.append(i)
number_to_test=number_to_test / i
#prime_list.append(i)
#prime_list.pop(-2) #remove the old number so that we only have the biggest
if prime_list==[1]:
print "This has no prime factors other than 1"
else:
print prime_list
return prime_list
#pdb.set_trace()
number_to_test=raw_input("What number would you like to find the greatest prime of?\n:")
#Convert the input to an integer
number_to_test=int(number_to_test)
#Pass the number to the oddnumbers function
odds=oddNumbers(number_to_test)
#Pass the return of the oddnumbers function to the findPrimes function
findPrimes(number_to_test , odds)
The simple solution is trial division. Let's work through the factorization of 13195, then you can apply that method to the larger number that interests you.
Start with a trial divisor of 2; 13195 divided by 2 leaves a remainder of 1, so 2 does not divide 13195, and we can go on to the next trial divisor. Next we try 3, but that leaves a remainder of 1; then we try 4, but that leaves a remainder of 3. The next trial divisor is 5, and that does divide 13195, so we output 5 as a factor of 13195, reduce the original number to 2639 = 13195 / 5, and try 5 again. Now 2639 divided by 5 leaves a remainder of 4, so we advance to 6, which leaves a remainder of 5, then we advance to 7, which does divide 2639, so we output 7 as a factor of 2639 (and also a factor of 13195) and reduce the original number again to 377 = 2639 / 7. Now we try 7 again, but it fails to divide 377, as does 8, and 9, and 10, and 11, and 12, but 13 divides 2639. So we output 13 as a divisor of 377 (and of 2639 and 13195) and reduce the original number again to 29 = 377 / 13. As this point we are finished, because the square of the trial divisor, which is still 13, is greater than the remaining number, 29, which proves that 29 is prime; that is so because if n=pq, then either p or q must be less than, or equal to the square root of n, and since we have tried all those divisors, the remaining number, 29, must be prime. Thus, 13195 = 5 * 7 * 13 * 29.
Here's a pseudocode description of the algorithm:
function factors(n)
f = 2
while f * f <= n
if f divides n
output f
n = n / f
else
f = f + 1
output n
There are better ways to factor integers. But this method is sufficient for Project Euler #3, and for many other factorization projects as well. If you want to learn more about prime numbers and factorization, I modestly recommend the essay Programming with Prime Numbers at my blog, which among other things has a python implementation of the algorithm described above.
the number 600851475143 is big to discourage you to use brute-force.
the oddNumbers function in going to put 600851475143 / 2 numbers in odd_list, that's a lot of memory.
checking that a number can be divided by an odd number does not mean the odd number is a prime number. the algorithm you provided is wrong.
there are a lot of mathematical/algorithm tricks about prime numbers, you should and search them online then sieve through the answers. you might also get to the root of the problem to make sure you have squared away some of the issues.
you could use a generator to get the list of odds (not that it will help you):
odd_list = xrange(1, number+1, 2)
here are the concepts needed to deal with prime numbers:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
http://en.wikipedia.org/wiki/Primality_test
if you are really stuck, then there are solutions already there:
Project Euler #3, infinite loop on factorization
Project Euler 3 - Why does this method work?
Project Euler Question 3 Help
Here is my Python code:
num=600851475143
i=2 # Smallest prime factor
for k in range(0,num):
if i >= num: # Prime factor of the number should not be greater than the number
break
elif num % i == 0: # Check if the number is evenly divisible by i
num = num / i
else:
i= i + 1
print ("biggest prime number is: "+str(num))
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
import math
def isPrime(x):
if x<2:
return False
for i in range(2,int(math.sqrt(x))):
if not x%i:
return False
return True
def largest_factor(number):
for i in range (2, int(math.sqrt(number))):
if number%i == 0:
number = number/i
if isPrime(number) is True:
max_val = number
break
print max_val
else:
i += 1
return max_val
largest_factor(600851475143)
This actually compiles very fast. It checks for the number formed for being the prime number or not.
Thanks
Another solution to this problem using Python.
def lpf(x):
lpf=2
while (x>lpf):
if (x%lpf==0):
x=x/lpf
else:
lpf+=1
return x
print(lpf(600851475143))
i = 3
factor = []
number = 600851475143
while i * i <= number:
if number % i != 0:
i += 2
else:
number /= i
factor.append(i)
while number >= i:
if number % i != 0:
i += 2
else:
number /= i
factor.append(i)
print(max(factor))
Here is my python code
a=2
list1=[]
while a<=13195: #replace 13195 with your input number
if 13195 %a ==0: #replace 13195 with your input number
x , count = 2, 0
while x <=a:
if a%x ==0:
count+=1
x+=1
if count <2:
list1.append(a)
a+=1
print (max(list1))
Here is my python code:
import math
ma = 600851475143
mn = 2
s = []
while mn < math.sqrt(ma):
rez = ma / mn
mn += 1
if ma % mn == 0:
s.append(mn)
print(max(s))
def prime_max(x):
a = x
i = 2
while i in range(2,int(a+1)):
if a%i == 0:
a = a/i
if a == 1:
print(i)
i = i-1
i = i+1

Categories

Resources