I am reading and solving through the exercises in the book Introduction to Computation and Programming Using Python by John Guttag (used in the MIT courses) and have a problem understanding why a while loop sets x = 1 at the beginning.
The exercise is asking to find a positive integer that is divisible by both 11 and 12. And the sample solution is:
x = 1
while True:
if x%11 == 0 and x%12 == 0:
break
x = x + 1
print(x, 'is divisible by 11 and 12')
#prints 132, which is divisible by both 11 and 12
I´m sorry that this is such a basic question, but I would appreciate if someone could explain to me the logic of setting x = 1 at the beginning, if x is the value that we are solving for in the first place. Also, I don´t understand the x = x+1 part.
Also, what is the notation I should use to tell a program to do something based on the condition "of all existing integers/values"... (followed by a for or while loop)? Is that what x = 1 possibly refers to?
This program tries to find the first strictly positive integer that is divisible by 11 and 12.
To do so, you need to start somewhere, and that's a positive number x = 1. If we set it to 0, then it will be our result, but we want a strictly positive number.
So we try to see if the new x is divisible, if not, we bump it by one.
A better program would be:
x = 1
while x%11 != 0 or x%12 != 0:
x = x + 1
print(x, 'is divisible by 11 and 12')
The algorithm works by verifying all positive integers one by one. It has to start somewhere, and a good place to start is the first positive integer: 1. Hence x = 1 - means "let's start from 1".
x = x + 1 sets the value of x to the next integer. Imagine for example that x is equal to 42. Then the statement conceptually translates to x = 42 + 1 and in turn: x = 43. That's how the algorithm jumps to the next integer to verify.
If you not set x=1 at the beginning you couldn't use x as variable because it does not exists in current execution scope.
Part with x = x+1 is for growing up x for next loop iteration.
As per the sample code, it starts to check a number which is divisible by both 11 and 12. So it starts with x=1 in a range of [1,ideally infinite). The x=x+1 keeps incrementing x by 1 until it encounters a number which is divisible by both the numbers viz 132, once it does, it breaks the infinite while loop.
Related
I am attempting to create a python game that finds whether an integer is prime or not by dividing it by all integers in range(1,100) and checking if the result yields a whole number. Is my approach correct, or is there a better way to do this?
This is the code I have written so far. Right now I am getting an error on line 3. Also, feedback on the efficiency of my method would be appreciated.
z = int(input("Please give me a number"))
x = range(1, 1000)
for i in x if int(z /= i) in range(0, 1000) :
print("non prime")
else:
print("prime")
You have a syntax error - you can't use an if in a for loop.
Overall the better way to do this is to use the modulus operator.
for i in range(2, z/2):
if z % i == 0:
print("non prime")
break
else:
print("prime")
In this code I'm making it more efficient by going up until half of z - the largest possible factor of a number is half of itself. It also breaks when it finds the first factor as there is no need to keep testing.
I also changed the range to start at 2 since you can't divide by 0 and 1 is a factor of everything.
For else is an unusual patten where the else only activates when the for isn't broken.
You can use a statement like the one below, which checks every item in the range x and if it divides, adds it to a list. It then checks the length of the list, if this is 2 or less then the number is prime, else it is not prime:
z = int(input("Please give me a number"))
x = range(1, 1000)
print("prime" if len([i for i in x if z%i==0]) == 2 else "non prime")
I am currently attempting to write a simple bit of python 3 code that allows the user to tell the program which prime number it wants to find and then return the number to the user. I have hit a roadblock because I need to check if the "newprime" value is in fact a prime, which requires me to divide the value by all the previous prime numbers ("primes") and then checking if the answer is a whole number or not. Here is the current program
import numpy
primes = [2]
print("the how many-th prime would you like to calculate?")
numberOfPrime = int( input() )
x = 0
while x <= numberOfPrime:
notprime = 0 #placeholder, should be all numbers which when divided by any of the set "primes" gives a whole number
while newprime == notprime:
newprime = primes[x] + 1
primes.append(newprime)
print(primes)
x += 1
print(primes[numberOfPrime], " is the ", numberOfPrime, "-th prime number", sep="")
As you can see, I added a comment where I would have to insert the missing part.
How do I best approach this?
I need to find all positive numbers that are divisible by 10 and less than n, i found a string with the same question but i have a hard time interpreting it as the user was using java so the codes are very different and confusing.
i tried to make a code by piecing together codes i've checked out but it only works if its divisible by other numbers, if its 10 it would keep going on forever with 0.
n = int(input("Enter a number: "))
x = 0
while x < n :
r = n % 10
if r % 10 != 0 :
x = x + r
print("positive numbers divisible by 10 ", x)
Below is simpler code which will help to get the list of numbers divisible by 10 and less than n:
n = int(input("Enter a number n: "))
divisibleBy10 = []
for i in range(0, n):
if i % 10 == 0:
divisibleBy10.append(i)
print(divisibleBy10)
You can do like this:
n = 100
i = 0
while i<n:
if i%10==0:
print(i)
i+=1
You can also try the following:
# grab the user's input
n = int(input('please enter a number: '))
# set x to 0, so the while loop can stop when 'n' is greater than '0'
x = 0
while n > x:
if n % 10 == 0:
print('{} is divisible by 10.'.format(n))
n -= 1
So basically the loop enters with the value that the user inputs, let's say 10.
Is 10 greater than 0? Yes (while loop executes), the if statement evaluates the remainder with the mod. The value is printed because the if statement evaluates True , the remainder is equal to zero. At last, n is subtracted by 1
Is 9 greater than 0? Yes (while loop executes), the if statement evaluates the remainder with the mod. The value is not printed because the if statement evaluates False , the remainder is not equal to zero. At last, n is subtracted by 1
Is 8 greater than 0? Yes (while loop executes), the if statement evaluates the remainder with the mod. The value is not printed because the if statement evaluates False , the remainder is not equal to zero. At last, n is subtracted by 1
...
And so on until n reaches 0, the while loop stops because 0 is not greater than 0.
This code below tries to reduce the number of loops. If 'x' is extremely large, it helps to optimize the solution. The idea is to not do the divisibility check for each number starting from 1 to n-1. Here, we use the fact that the least positive number divisible by 10 is 10. The next number of interest is 10 + 10 = 20, there by skipping numbers 11 to 19. This helps improve the performance.
x = input('Enter any number ')
y = 10
while y < x:
print(y)
y = y + 10
I think use inline for loop:
print([i for i in range(10,n,10) if i % 4 == 0])
I'm working on a program which will found the nth. prime number. For example, By listing the first six prime numbers: 2, 3, 5, 7, 11 and 13, we can see that the 6th prime is 13. I'm trying to making an algorithm, like, if I want to see 50th prime, I will add 1 to ends of the range() function. I'm using this algorithm to find primes at the moment;
cnt = 1
print (2)
for x in range(3,40,2):
div = False
for y in range(2,round(x**0.5)+1):
if x%y == 0:
div = True
if div == False:
print (x)
cnt += 1
print ("\nThere is {} prime numbers.".format(cnt))
You see that, I put 40. But I want to put n there, so for example, untill reaching the 50th prime, add +1 to n. But it's not going to like that, if I tried something like;
cnt = 1
n = 40 #example
while cnt<50:
for x in range(3,n,2):
#codes
if div == False:
n += 1
I thought when the program finds a prime, it will add +1 to n and while loop will process untill find the 50th prime. But it didn't, primes are wrong if I use this one also, nothing relevant what I want to do.
How to make this algorithm, obviously changing the last element of range() function does not working.
Is there better/elegant algorithm/way? If I want to find 200.000th prime, I need faster codes.
Edit: I was working with lists first but, I got MemoryError all the time when working with big numbers. So I pass that and using a variable that counting how much primes are there cnt.
Here is a much faster version
primes = []
primecount = 0
candidate = 2
while primecount<50:
is_prime = True
for prime in primes:
if candidate%prime == 0:
is_prime = False
break
elif candidate < prime**2:
break
if is_prime:
primes.append(candidate)
primecount += 1
candidate += 1
print primes[-1]
note small edit adding the candidate<prime**2 test that OP included but I neglected initially.
Your code is going to be very slow for several reasons. If 2 divides a number you know it's not prime, but you're still checking whether 3 or 4 or 5... divides it. So you can break out as soon as you know it's not prime. Another major issue is that if 2 does not divide a number, there's no reason to check if 4 divides it as well. So you can restrict your attention to just checking if the primes coming before it divide it.
In terms of run time:
First off, for backwards compatibility with python 2, I added an int() around your rounding of root x.
From what I understand of your question, you are looking for something like this:
cnt = 1
maximum=50 #Specify the number you don't want the primes to exceed
print (2)
n=20 #highest number
while cnt<maximum: #
for x in range(3,n,2): #using "n" as you hoped
div = False
for y in range(2,int(round(x**0.5)+1)):
if x%y == 0:
div = True
if div == False:
if x<maximum: #we only want to print those up to the maximum
print str(x)
else: #if it is greater than the maximum, break the for loop
break
cnt += 1
break #break the while loop too.
print ("\nThere are {} prime numbers.".format(cnt))
This gave me the correct primes. As for better/more elegant solutions. If by better you want speed, use a library that has an optimized, or look at this for an example of a fast program. Elegance is subjective, so I will leave that to the rest of the internet.
I need help with a program in python 3.3 that is supposed to do Russian peasant multiplication/ancient Egyptian multiplication. The assignment says," If "A" and "B" are the two integers to be multiplied, we repeatedly multiply "A" by 2 and divide "B" by 2, until "B" cannot divide any more and is not zero (integer division). During each set of multiplying "A" and dividing "B", if the value of "B" is an odd number, you add whatever the "A" value is to a total. At the end, the sum of all the "A" values (when "B" is odd) should be equal to the product of the original "A" and "B" inputs. In short, sum up all the "A" values for which "B" is odd and it will be equal (or close) to the product of "A" and "B".
edit
I may have phrased some of the question wrong.
Here is an example:
If "A" is 34, and "B" is 19, multiplying "A" by two and dividing "B" by two each line.
"A" "B"
(34) (19) ("B" is odd, add "A" to total)
(68) (9) ("B" is odd, add "A" to total)
(136) (4) ("B" is even, ignore "A" value)
(272) (2) ("B" is even, ignore "A" value)
(544) (1) ("B" is odd, add "A" to total)
When you sum all the values of "A" for which "B" is odd, you get (34 + 68 + 544 = 646),
which is equal to just multiplying "A" and "B", (34 * 19 = 646).
The part I'm having trouble with is adding "A" to a total whenever "B" is an odd number.
This is what I have so far,
x = int(input("What is the first number? "))
y = int(input("What is the second number? "))
answer = 0
while y != 0:
if (y%2 != 0):
x*2
y//2
answer == answer + x
if (y%2 == 0):
x*2
y//2
print("the product is",(answer))
I'm very new to python and programming, so any help and/or explanations of why its wrong would be greatly appreciated.
you need to add x to answer first, then update x
here is the correct code
x = int(input("What is the first number? "))
y = int(input("What is the second number? "))
answer = 0
while y != 0:
if (y%2 != 0):
answer=answer+x
x=x*2
y=y//2
if (y%2 == 0):
x=x*2
y=y//2
print("the product is",(answer))
I'm not familiar with the algorithm you are trying to implement, but I have made a few modifications to your code.
x = int(input("What is the first number? "))
y = int(input("What is the second number? "))
answer = 0
# != 0 is redundant: y is True if it is not 0
while y:
# no need to have parentheses here
if y % 2:
# this needs to be an assignment, not a check for equality
answer += x # shorthand for answer = answer + x
# These happen every time, so does not need to be inside the if
# these also need to be an assignment, not just an expression
x *= 2
y /= 2
# total was never defined
print("the product is", (answer))
A side note. Frankly, I did not know about the algorithm until now. The more it surprises me it was used by ancient Egyptians or in old Russia. (Actually, I tend to believe that the Russian origin is more probable as it seem that Slavic nations are directly related to old Etrusks).
The old origin surprises me because it actually is a plain hand-made multiplication that you learned in the basic school. The only difference is that the numbers are converted to binary representation first. Rather machine oriented, isn't it? :)
For the numbers in the question, th 34 in decimal representation is equal to 100010 in binary, the 19 in decimal is 10011 in binary. Now the plain basic school multiplication on paper:
100010
x 10011
------------
100010 i.e. 100010 times 1
100010 1000100 times 1
000000 10001000 times 0
000000 100010000 times 0
100010 1000100000 times 1
------------ ^ binary digits of the multiplier
1010000110 (reminder of division by 2)
^ adding the zero means multiplying by 2
i.e. sum only when 1 is the reminder of division
It seems that the one who designed the metod (in ancient times) knew what the binary numbers are.
The last time you add x is when y is equal to 1. If you keep halving until the number
reaches 0, it will take a very large number of iterations (logically, it will take
forever).
Think about 2x2. If you double x to 4, and halve y to 1, x is your answer.
In other words, think of y as how many of x I need to yield answer. Since you can't multiply, only add/double/halve, you have a choice - you can wait until y is 2 and then add doubled value of x, OR you can wait until y is 1 and simply add value of x. The latter is simpler and clearer, that's all.
I think it's clearer in this case to use a while True loop:
def mult2(x, y):
answer = 0
while True:
if y % 2:
answer += x
if y < 1:
break
x *= 2
y //= 2
print("the product is", answer)
Calling function recursively:
def mult2(x, y):
"""aka 'Russian peasant method'; allowed: addition, halving, doubling."""
if y==1:
return x
else:
add = x if y%2 else 0
return mult2(x*2, y//2) + add
the output is a normal mutiplication display. Please share the code where the output is also displayed showing the Russian Peasent method.
Output should be something like this:
If "A" is 34, and "B" is 19,
(34) (19) ("B" is odd, add "A" to total)
(68) (9) ("B" is odd, add "A" to total)
(136) (4) ("B" is even, ignore "A" value)
(272) (2) ("B" is even, ignore "A" value)
(544) (1) ("B" is odd, add "A" to total)
When you sum all the values of "A" for which "B" is odd, you get (34 + 68 + 544 = 646), which is equal to just multiplying "A" and "B", (34 * 19 = 646).