I was exercising to improve my coding but when I try to use this code and run, terminal just freezes and not giving any error at all, I cant do anything either until I press ctrl+c. Cause of its not giving error I don't know what did I wrong.
# 31. Write a Python program to compute the greatest common divisor (GCD) of two positive integers.
def findGCD(num,num1):
numDivided = 0
num1Divided = 0
while True:
num/2
numDivided+=1
num1/2
num1Divided+=1
if num and num1 == 1 or 0:
break
gcd = numDivided*num1Divided
print(gcd)
findGCD(101,102)
There are numerous mistakes including the incorrect if statement referred to above. num/2 will calculate something but this will be a float value if num is odd; then you do nothing with the result; same for num1/2. To find GCD you have to use integer arithmetic. Incidently 101 and 102 have only the GCD of 1 so maybe not the best example. The code below works. I suggest you paint it into https://pythontutor.com/visualize.html#mode=edit to step through the code and see how it works.
def findGCD(num, num1):
if num > num1:
hold = num1
else:
hold = num
for i in range(1, hold + 1):
if ((num % i == 0) and (num1 % i ==0)):
gcd = i
return gcd
this code is supposed to take slope (m) and y-intercept (b) of two lines and checks if these two line hit each other or not.
the problem is my while loop is infinite although I have condition and break statement
print("enter the first m: ")
m = input() # m = slope
print("enter the first b: ")
b = input() # b = y-intercept
print("enter the second m: ")
m1 = input()
print("enter the second b: ")
b1 = input()
sub_m = int(m) - int(m1) #sub = subtract
sub_b = int(b) - int(b1)
if (sub_m == 0):
print("parallel")
x = float(-sub_b / sub_m)
r = round(x, 1)
i = 0.0
while i != r:
print(r, i)
if (i == r):
print("\nhit piont: ", i)
break
if (sub_m > 0 and sub_b > 0):
i -= 0.1
elif (sub_m < 0 and sub_b < 0):
i -= 0.1
else:
i += 0.1
Everyone here seems to be adamant on using some fancy tricks to make floating comparison works. Why not just multiply it all by 10 and get rid of floats altogether? :-)
I don't know if it is the fastest solution but it should have less corner cases.
i = 0
while True: # <- condition removed to allow the "hit point" if to work
print(r, i / 10)
if (i == r * 10):
print("\nhit piont: ", i / 10)
break
if (sub_m > 0 and sub_b > 0):
i -= 1
elif (sub_m < 0 and sub_b < 0):
i -= 1
else:
i += 1
Running this in my debugger showed that you're getting floating point representation errors. This means that although technically you should be getting numbers perfectly rounded to 1 decimal given that you're applying increments of 0.1, in reality this isn't the case:
As you can see, r = -2.0 and i = -2.00...4, thus at no point is r == i.
You can fix this by adding another round statement at the end:
print("enter the first m: ")
m = input() # m = slope
print("enter the first b: ")
b = input() # b = y-intercept
print("enter the second m: ")
m1 = input()
print("enter the second b: ")
b1 = input()
sub_m = int(m) - int(m1) #sub = subtract
sub_b = int(b) - int(b1)
if (sub_m == 0):
print("parallel")
x = float(-sub_b / sub_m)
r = round(x, 1)
i = 0.0
while i != r:
print(r, i)
if (sub_m > 0 and sub_b > 0):
i -= 0.1
elif (sub_m < 0 and sub_b < 0):
i -= 0.1
else:
i += 0.1
i = round(i, 1) # <- this
print(f"Hit pt: {i}")
HOWEVER: This is still error prone, and I recommend finding a way to avoid if i==r altogether in the code. If i is lower than r, exit the loop when it finally becomes bigger, and viceversa. Its best practice to avoid using the == condition when comparing floats, and to find a way to use <= and >=.
This is a question of granularity and floating-point precision. You're incrementing i in steps of 0.1 and then checking, at each step, if i == r. But what if r is not an integer multiple of 0.1? Then i will never exactly equal r, and your break will never be triggered.
By the way, your while condition and your if condition are mutually exclusive; if i and r are equal, you never enter the loop, and consequently won't have to/be able to break out of it. What you want is probably a genuine infinite loop with while True.
First of all, your while loop breaking condition contradicts your if() break condition. so it will never get to match the if condition. So it will never print hit point, because it will break the while loop when l==r, either it will never be l==r because of precision and loop infinite, so in both situations if condition never match. And comparing a floating value to break a loop is not ideal.
Instead of using math.floor, the task for me is to write a round down function. My thought is to:
test whether it is a number → whether the number is positive → whether the decimal part >= 0.5 → if yes, print [ round(number) - 1], otherwise print [round(number)]
I basically have two problem.
The first is how to test whether an input is positive or negative?
The second is how to write multiple statements with if/elif/else. Because I have two layers of conditions, I don't know what to use.
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
#2 is input positive?
#3 s > 0+ decimal >= 0.5;
if s > 0:
if s - round(s) < 0:
print (round(s) - 1)
else:
print(round(s)) #decimal < 0.5
else: # s < 0 + decimal >= 0.5
if s - round (s) > 0:
print (round(s) + 1)
else: # decimal < 0.5
print (round(s))
I expect to round down input.
The int function truncates a decimal number allowing you to round down to the next integer.
def round_down(x):
return int(x)-1 if x < 0 else int(x)
round_down(3.5) # 3
round_down(-4.6) # -5
x = 25
epsilon = 0.01
step = 0.1
guess = 0.0
while guess <= x:
if abs(guess**2 -x) >= epsilon:
guess += step
if abs(guess**2 - x) >= epsilon:
print('failed')
else:
print('succeeded: ' + str(guess))
I am given this Python program which attempts to calculate the square root of a number x. For some reason, this program loops indefinitely and I'm not sure why.
There are only finitely many values of guess, because, after guess>x (i.e. when guess>=25.1,, the while loop then stops). The while command in the middle of the program is the only thing that loops, so what is happening?
You only increment guess when the condition abs(guess**2 -x) >= epsilon is true. That condition is false when guess = 5.0. At that point guess never changes anymore but guess <= x is still true and you enter an infinite loop:
>>> x = 25
>>> epsilon = 0.01
>>> guess = 5.0
>>> abs(guess**2 - x)
0.0
>>> abs(guess**2 - x) >= epsilon
False
Starting at guess = 0.0 and incrementing by 0.1 means that your loop executes 50 times before reaching that point, after which guess never changes again.
In reality, guess is not 5.0 exactly because adding an approximation of 0.1 (which can't be represented exactly using binary fractions), gives you a value a small amount lower:
>>> guess = 0.0
>>> for _ in range(50):
... guess += 0.1
...
>>> guess
4.999999999999998
but that difference is still smaller than epsilon.
You probably want to break the while loop when you have reached within epsilon distance of the target:
while guess <= x:
if abs(guess**2 -x) < epsilon:
break
guess += step
Even if you change the while condition to < instead of <=, it will still loop indefinitely, because of floating point inaccuracy.
Although you add steps of 0.1, the guess value will not become exactly 5, but 4.999999999999998, at which point the loop will continue to run without entering in the if block.
This is at least what I see happening here
I am now doing the MIT opencourse thing, and already the second assignment, I feel it has left me out in the cold. http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset1a.pdf
The specifics of it, are to write something that can calculate the 1000th prime number. We only know about the print, ==, =, 1=,if, else, elif, while, %, -,+,*,/, commands I think. We also don't yet know about importing libraries.
My Idea of how it would work is to take an odd number and try to divide it by, 3,4,5,6,7,8,9 and if %n !=0, then add a number to NumberofPrimes variable starting with 11 as the base of the tests, and assigning it a base value of 4 at the base of NumberofPrimes, though I don't know if that is even right, because I wouldn't know how to display the 1000th prime number.
Am I close?
The latest incarnation of it is as follows:
##calculate the 1000th prime number
potprime = 3
numberofprime = 1
cycle = if potprime%3 = 0:
break
if potpimre%4 = 0:
break
if potprime%5 = 0:
break
if potprime%6 = 0:
break
if potprime%7 = 0:
break
if potprime%8 = 0:
break
if potprime%9 = 0:
break
numberofprime + 1
potprime + 1
if potprime%2 == 0:
potprime = potprime + 1
if potprime != 0:
cycle
Where exactly am I going wrong? Walk me through it step by step. I really want to learn it, though I feel like I am just being left out in the cold here.
At this point, it would be more beneficial for me to see how a proper one could be done rather than doing this. I have been working for 3 hours and have gotten nowhere with it. If anybody has a solution, I would be more than happy to look at it and try to learn from that.
Looks like I am late
It is quite straight forward that if a number is not divisible by any prime number, then that number is itself a prime number. You can use this fact to minimize number of divisions.
For that you need to maintain a list of prime numbers. And for each number only try to divide with prime numbers already in the list. To optimize further it you can discard all prime numbers more than square root of the number to be tested. You will need to import sqrt() function for that.
For example, if you test on 1001, try to test with 3, 5, 7, 11, 13, 17, 19, 23, 29 and 31. That should be enough. Also never try to find out if an even number is prime. So basically if you test an odd number n, then after that test next number: (n + 2)
Have tested the below code. The 1000th prime number is 7919. Not a big number!!
Code may be like:
from math import sqrt
primeList = [2]
num = 3
isPrime = 1
while len(primeList) < 1000:
sqrtNum = sqrt(num)
# test by dividing with only prime numbers
for primeNumber in primeList:
# skip testing with prime numbers greater than square root of number
if num % primeNumber == 0:
isPrime = 0
break
if primeNumber > sqrtNum:
break
if isPrime == 1:
primeList.append(num)
else:
isPrime = 1
#skip even numbers
num += 2
# print 1000th prime number
print primeList[999]
The following code is gross, but since 1000 is indeed a small index, it solves your problem in a fraction of a second (and it uses only the primitives you are supposed to know so far):
primesFound = 0
number = 1
while primesFound < 1000:
number = number + 1 # start from 2
# test for primality
divisor = 2
numberIsPrime = True
while divisor*divisor <= number: # while divisor <= sqrt(number)
if number % divisor == 0:
numberIsPrime = False
break
divisor = divisor + 1
# found one?
if numberIsPrime:
primesFound = primesFound + 1
print number
You can test the solution here.
Now you should find a more efficient solution, optimize and maybe go for the 1000000-th prime...
For one thing, I'm pretty sure that in Python, if you want to have an if statement that tests whether or not A = B, you need to use the == operator, rather then the =.
For another thing, your algorithm would consider the number 143 to be prime, even though 143 = 11 * 13
You need keep track of all the prime numbers that you have already computed - add them to an array. Use that array to determine whether or not a new number that you are testing is prime.
It seems to me that you are jumping into the deep-end after deciding the kiddy-pool is too deep. The prime number project will be assignment 2 or 3 in most beginning programming classes, just after basic syntax is covered. Rather than help you with the algorithm (there are many good ones out there) I'm going to suggest that you attempt to learn syntax with the python shell before you write long programs, since debugging a line is easier than debugging an entire program. Here is what you wrote in a way that will actually run:
count = 4
n = 10 #I'm starting you at 10 because your method
#says that 2, 3, 5, and 7 are not prime
d = [2, 3, 4, 5, 6, 7, 8, 9] #a list containing the ints you were dividing by
def cycle(n): #This is how you define a function
for i in d: #i will be each value in the list d
if not n%i: #this is equal to if n%i == 0
return 0 #not prime (well, according to this anyway)
return 1 #prime
while count < 1000:
count += cycle(n) #adds the return from cycle to count
n += 1
print n - 1
The answer is still incorrect because that is not how to test for a prime. But knowing a little syntax would at least get you that wrong answer, which is better than a lot of tracebacks.
(Also, I realize lists, for loops, and functions were not in the list of things you say you know.)
Your code for this answer can be condensed merely to this:
prime_count = 1
start_number = 2
number_to_check = 2
while prime_count <= 1000:
result = number_to_check % start_number
if result > 0:
start_number +=1
elif result == 0:
if start_number == number_to_check:
print (number_to_check)
number_to_check +=1
prime_count +=1
start_number =2
else:
number_to_check +=1
start_number = 2
To answer your subsequent question, 'How do I keep track of all the prime numbers?
One way of doing this is to make a list.
primeList = [] # initializes a list
Then, each time you test a number for whether it is prime or not, add that number to primeList
You can do this by using the 'append' function.
primeList.append( potprime ) # adds each prime number to that list
Then you will see the list filling up with numbers so after the first three primes it looks like this:
>>> primeList
[11, 13, 17]
Your math is failing you. A prime number is a number that has 2 divisors: 1 and itself. You are not testing the numbers for primality.
I am very late on this but maybe my answer will be of use to someone. I am doing the same open course at MIT and this is the solution I came up with. It returns the correct 1000th prime and the correct 100,000th prime and various others in between that I have tested. I think this is a correct solution (not the most efficient I am sure but a working solution I think).
#Initialise some variables
candidate = 1
prime_counter = 1
while prime_counter < 1000:
test = 2
candidate = candidate + 2
# While there is a remainder the number is potentially prime.
while candidate%test > 0:
test = test + 1
# No remainder and test = candidate means candidate is prime.
if candidate == test:
prime_counter = prime_counter + 1
print "The 1000th prime is: " + str(candidate)
While I was at it I went on and did the second part of the assignment. The question is posed as follows:
"There is a cute result from number theory that states that for sufficiently large n the product of the primes less than n is less than or equal to e^n and that as n grows, this becomes a tight bound (that is, the ratio of the product of the primes to e^n gets close to 1 as n grows).
Computing a product of a large number of prime numbers can result in a very large number,
which can potentially cause problems with our computation. (We will be talking about how
computers deal with numbers a bit later in the term.) So we can convert the product of a set of primes into a sum of the logarithms of the primes by applying logarithms to both parts of this conjecture. In this case, the conjecture above reduces to the claim that the sum of the
logarithms of all the primes less than n is less than n, and that as n grows, the ratio of this sum to n gets close to 1."
Here is my solution. I print the result for every 1,000th prime up to the 10,000th prime.
from math import *
#Initialise some variables
candidate = 1
prime_counter = 1
sum_logs = log(2)
while prime_counter < 10000:
test = 2
candidate = candidate + 2
# While there is a remainder the number is potentially prime.
while candidate%test > 0:
test = test + 1
# No remainder and test = candidate means candidate is prime.
if candidate == test:
prime_counter = prime_counter + 1
# If the number is prime add its log to the sum of logs.
sum_logs = sum_logs + log(candidate)
if prime_counter%1000 == 0:
# For every 1000th prime print the result.
print sum_logs," ",candidate," ",sum_logs/candidate
print "The 10000th prime is: " + str(candidate)
Cheers,
Adrian
I came up with this solution in my interview, but I didn't get the job :( It has about 1/100 less iterations than the solution above:
from math import *
MAX_IDX=1000
MAX_IDX-=1
num_iter=0
l_pirme_list=[3]
candidate=l_pirme_list[0]
prime_counter=1
while prime_counter < MAX_IDX:
candidate+=2
#Cut the binary number in half. This is quite faster than sqrt()
bin_candidate=format(candidate, "2b")
max_prime_search=int(bin_candidate[:len(bin_candidate)/2+1],2)+1
# max_prime_search=sqrt(candidate)+1
candidate_is_prime=1
for prime_item in l_pirme_list:
num_iter+=1
if candidate % prime_item==0:
candidate_is_prime=0
break
elif prime_item > max_prime_search:
candidate_is_prime=1
break
if candidate_is_prime:
prime_counter+=1
l_pirme_list.append(candidate)
l_pirme_list.insert(0,2)
print "number iterations=", num_iter
print l_pirme_list[MAX_IDX]