Homework 3.9, 3.11
def sqrt(N,p): # sqrt with precision
# to find the closest int
low = 0
end = N
ans = 1
while low <= end:
mid = int((low + end) / 2)
if mid **2 == N:
ans = mid
break
if mid ** 2 < N:
low = mid + 1
ans = mid
else:
end = mid - 1
# calculating for precision
incre = 0.1
for i in range(p):
while ans ** 2 <= N:
ans += incre
ans -= incre
incre /= 10
return round(ans,p)
from math import sqrt as sq
test_cases = [0,1,4,85248289,22297284,18939904,91107025,69122596,9721924,37810201,1893294144,8722812816,644398225]
answers = [int(sq(x)) for x in test_cases]
def checkValid():
for i in range(len(test_cases)):
if sqrt(test_cases[i],0) == answers[i]:
print("Check number {} passed".format(i+1))
else:
print("Check number {} failed".format(i+1))
checkValid()
for i in range(10):
print(sqrt(2,i))
- What does the algorithm do? Please explain in words.
If num divided by num2 has no remainder, return True, else, return False
- What if I put in 30 as num and 4 as num2. What would be the output?
False
What is the output of this algorithm?
If Temp is higher than 90, it prints it's too hot outside, if it is between 65 and 90, it prints I will go outside, else, it prints it's too cold outside
temp = 95
if (temp >= 90):
print("it is too hot outside")
else:
if (temp >= 65):
print("I will go outside")
else:
print("it is too cold outside")
What is the output of this algorithm? it looks similar but the output is different!
If Temp is higher than 90, it prints it's too hot outside, if Temp is higher than 65, it prints I will go outside, if Temp is lower than 65, it prints it's too cold outside
temp = 95
if (temp >= 90):
print("it is too hot outside")
if (65 <=temp < 90):
print("i will go outside")
if (temp < 65):
print("it is too cold outside")
Task: Write an algorithm in python that sums up the first 5 odd integers. You can use the following code as a starter.
sum = 0
counter = 1
for i in range (0, 5):
sum = sum + counter
counter = counter + 2
Homework
Create an algorithm that will start with any positive integer n and display the full sequence of numbers that result from the Collatz Conjecture. The COllatz Conjecture is as follows:
- start with any positive integer
- if the number is even, divide by 2
- if the number is odd, multiply by 3 and add 1
- repeat steps 2 and 3 until you reach 1
Example: if the starting number was 6, the output would be 6, 3, 10, 5, 16, 8, 4, 2, 1
def procedure(num):
counter=0
while num !=1:
print(num)
if num%2==0:
num//=2
else:
num*=3
num+=1
counter+=1
print(num)
print("After "+str(counter)+ " iterations")
procedure(int(input()))