Project Euler using Python, Regarding definition of multiples - python

I started programming recently, my first language being python. I know just the basics of the language including conditionals, loops, range and some other functions.
I tried to solve project euler's problem 1 using python. The problem statement is as follows:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Here's my solution:
z=0
for x in range(0,1000,1):
if type(x%3)==int or type(x%5)==int:
z=x+z
print z
The answer i get is 499500 which is wrong. I tried searching for an answer and found that replacing the third line of my solution:
if type(x%3)==int or type(x%5)==int
with
if x%3==0 or x%5==0
yields the correct answer which is 233168.
Why is my code wrong? So far as I'm aware, a multiple need not leave the remainder as zero. For instance, 255 is a multiple of 5. But 255%5 does not leave the remainder as zero. So how does the line if x%3==0 or x%5==0 correct the answer when in fact, it ignores the definition of multiples.
Or perhaps I have wrongly assumed what multiples are. Please help me.
Thank you.

The problem with your original code, is that Modulo operation with natural numbers always yields a natural number.
print type(4%3)
#print <type 'int'>
print type(4%3)==int
#print True
So, what you are doing is basically summing all numbers between 0 and 1000:
print sum(range(0,1000,1))
#prints 499500
Hope that helps

a is a multiple of b iff a = k b with k an integer. Then % is modulo, which is defined like that:
a % b = z iff a = k b + z with k (and z) integers (and 0 <= z < b)
Therefore if z= 0, then a = k b and a is a multiple of b.

Related

Syntax for Greatest Common Divisor - Python

The program below was more precise and shorter than mine, and thus more appealing. I understand mod (%), but the rest of the syntax on the line noted is confusing me. Does anyone know what this syntax is called or how it works?
The problem asked to create a function to find the greatest common divisor (gcd) for two integers, which is the largest number that divides both numbers without a remainder.
For example, the gcd of 20 and 12 is 4.
def gcd(x, y):
while y != 0:
(x, y) = (y, x % y) ## What is happening here? What's this syntax called?
return x
Link to where I found this program: How to calculate a mod b in python?
Thank you so much for your help!
You have stumbled upon tuple assignments!
In a nutshell, in python, You can assign groups of variables so long as you are assigning them from a structure with the same format
Here is a simpler illustration of what is happening:
a,b = 3,5
#a is now equal to 3 and b is now equal to 5
#You literally could go:
# a = 3
# b = 5
#And it would be logically equivalent
a+b
Returns
>>>8
In your function, you are assigning the value of y (the second parameter of the function) to the variable x, and updating the value of y to the remainder of x/y.
I hope this helps.

I'm brand new and working on Project Euler #2 in python

The goal is to sum up every even number up to 4 million.
I thought this would work but the program gets stuck running. Think it has to do with the if statement, but lost otherwise. Here's what I have.
list = []
a, b = 0, 1
while b <40:
if b%2 == 0:
list.append(b)
a, b = b, a+b
t=sum(list)
print(t)
This here is your biggest problem:
a, b = b, a+b
It has so much potential to mess up your loop! And like others mentioned it doesn't even update anything when b is odd, only when it is even, and then you're stuck.
Why not do this the simple way, with range:
mysum = sum([i for i in range(0, 40, 2)])
Will take care of everything with one line (and of course, replace 40 with 4,000,001 for your question, if you want to include the number 4,000,000 as well. If you just want everything up to it but not to include it, use just 4,000,000)
a, b = b, a+b
This line only runs if b % 2 == 0. I think you meant to run it every time. It should be indented one layer further out.
One can also use the mathematics rule where the sum of integers between 1 and n is equal to n*(n+1)/2. If we want to sum only even numbers, it is like considering only half the number to sum and multiply the result with two.
fSumEvenNumbers = lambda x: (x//2)*(x//2+1)
This would give
fSumEvenNumbers(40000000)
which is equivalent to
(2e7)**2 + 2e7
4e14 + 2e7
400000020000000

Python: Nesting an "If" statement inside a "while" loop?

I'm new to Python, which is why I'm having trouble on a problem which others might find easy.
Background to this problem: Euler Project, question 2. The problem essentially asks us to add all the even terms in the Fibonacci sequence, so long that each term is under 4,000,000. I decided to do the problem a little differently than what many solutions online show, by calculating the nth Fibonacci term from a closed formula. For now, suppose this function is called Fibonacci(n).
What I'd essentially like to do is loop through an unknown amount of integers that represent the indexes of the Fibonacci set (i.e., 1, 2, 3, 4... etc) and plug each value into Fibonacci(n). If the result has no remainder when divided by 2, then add this Fibonacci number to some value initially set at 0.
Here's what I have so far:
def Fibonacci(n):
return (1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n))
i=0
FibSum = 0
nFib = 0
while (nFib <= 10):
nFib = Fibonacci(i)
if(nFib%2==0):
FibSum += nFib
i += 1
print FibSum
(Yes, as you can see, I'm constraining the Fibonacci sequence to end at 10 as opposed to 4,000,000; this is done merely for testing's sake.)
Now, here's my problem: when I run this code, I get 2.0 instead of 10.0 (2 and 8 are the two Fibonacci numbers that should be added together).
How come? My guess is that the loop stops after it gets to the third Fibonacci number (2) and doesn't continue beyond that. Does anyone see something wrong with my code?
Please comment if you have any further questions. Thanks in advance.
Solution provided by Gal Dreiman is fine but, conversion with in function is more better, below is your revised code:
def Fibonacci(n):
return int((1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n)))
You have a floating point problem (which you can read on here)- the returned value 'nFib' is not an integer and not a rounded value. I ran your code and added print for this value in every iteration and got:
0.0
1.0
1.0
2.0
3.0000000000000004
5.000000000000001
8.000000000000002
13.000000000000002
The solution for this is to modify your code as the following:
nFib = int(Fibonacci(i))
After that I got the output: 10
The problem is with nFib%2==0 comparison. Here you try to compare the float LHS with integer 0. So either modify the if loop as below or modify the return as return int((1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n))).
>>> def Fibonacci(n):
... return (1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n))
...
>>> i=0
>>> FibSum = 0
>>> nFib = 0
>>> while (nFib <= 10):
... nFib = Fibonacci(i)
... if(int(nFib%2)==0):
... FibSum += nFib
... i += 1
...
>>> print FibSum
10.0

I'm trying to find the sum of all primes below 2 million in python

ls = []
total = 0
for i in range(0,2000000):
ls.append(i)
for i in range(2,2000000):
for x in range(2,int(float(2000000/i)+0.5)):
ls[int(float(i*x))] = 0
ls[1] = 0
for j in range(0,2000000):
total += ls[j]
print total
This code is giving me the wrong answer. It includes large numbers that are not prime. It includes 25 more numbers than there are prime numbers.
Your algorithm is giving the wrong result, couldn't figure out what approach do you use, it would be better if you could give more details.
There is an algorithm called Sieve of Eratosthenes algorithm to generate prime number effectively. You find that algorithm explained in this thread, with details to write the algorithm.
import math
def primeNumbers(n):
A = range(2, n + 1)
B, C= [],A
while C[0]< math.sqrt(n):
firstElement= C[0]
B+= [firstElement]
C= [x for x in C if x%firstElement!=0]
return B+C
t= sum(primeNumbers(2000000)) #you summ the prime numbers numbers
print t
The problem is with this line:
for x in range(2,int(float(2000000/i)+0.5)):
float(2000000/i) doesn't do much in this context, did you mean float(2000000)/i? You're still doing integer division and then converting the result to float. So, when i is 947, this returns 2111.0 instead of 2111.93. As a result, adding 0.5 to that and calling int() effectively does nothing and you still end up with 2111.
This then ends up running the loop till 2110, so you fail to mark 947 * 2111, which gives you a false positive.
You can rewrite the loop slightly to fix this:
for i in range(2,2000000):
for x in range(2 * i, 2000000, i):
ls[x] = 0
This way, instead of dividing and then multiplying, you're simply going through and marking all the multiples of i until 2000000.
Obviously, there are other (better) ways to solve the problem, but I just wanted to point out how you can improve your current solution.

List of numbers whose squares are the sum of two squares

I've just started learning Python and have started doing some problems just to help buid my skills however I am pretty stuck on this question.
Make a list containing all positive integers up to 1000 whose squares can be expressed as a sum of two squares, (i,e., integers p for which p^2=m^2+n^2, where m and n are integers greater than 0.)
Hints: There are several approaches. You might find it helpful to have a list of all the square numbers. The in operator might be useful.
Here's the code that I've come up with so far:
numbers=xrange(1001)
numbers_squared=[x**2 for x in numbers]
a=[]
for x in numbers_squared:
for b in numbers_squared:
if (x+b)**.5 <= 1001:
a.append(x+b)
print a
The problem I get with this is that Python takes years to do these calculations (I've waited about ten minutes and it's still printing numbers). Any hints on how to solve this would be very appreciated.
p.s. The main point is to use lists. Also hints would be more appreciated than the solution itself.
Thank You!
First of all, you aren't solving the problem. You need to do a check to make sure (x+b)**.5 is actually an integer.
Secondly, if you are printing numbers, you have already calculated out all the numbers. Doing the above will decrease the time required for this step.
how about a list comprehension?
calculate for c in range(1,1011)
for b in range (1, c)
for a in range (1, b)
as follows:
x = [(a,b,c) for c in range(1,1001) for b in range(1, c) for a in range(1,b) if a**2+b**2==c**2]
print x
I have timed this and it takes 46 seconds to complete on my computer
This might work:
def isSumOfSquares(n):
"""return True if n can be expressed as the sum of two squares; False otherwise"""
for a in xrange(1,n):
b = n-(a**2)
if b<=0:
return False
elif not math.sqrt(b)%1:
return True
return False
answer = [i for i in xrange(1,1001) if isSumOfSquares(i**2)]
Let me know if this works for you
I just answered this elsewhere!
import math
def is_triple(hypotenuse):
"""return (a, b, c) if Pythagrean Triple, else None"""
if hypotenuse < 4:
return None
c = hypotenuse ** 2
for a in xrange(3, hypotenuse):
b = math.sqrt(c - (a ** 2))
if b == int(b):
return a, int(b), hypotenuse
return None
>>> results = [x for x in range(1001) if is_triple(x)]
>>> len(results)
567
Runs almost instantly.

Categories