Am I using the modulo operator incorrectly? - python

If my understanding is correct, 5 % 5 should equal 0. However when i run this code:
endless = 0
while endless == 0:
n = int(input("Provide a number here: "))
count = 0
sum = 0
while count < n:
if 1+count % 3 == 0 | 1+count % 5 == 0:
sum += 1 + count
count += 1
if count >= n:
print(sum)
It always returns 0, which implies that 1+count % 3 or 1+count % 5 never equals 0. What did i miss?
EDIT:
I seem too have missed fundamental maths somehow.

Dont use bitwise OR, and use paranthesis (operator precedence)!
Try:
(1+count) % 3 == 0 or (1+count) % 5 == 0:
^ ^ ^^ ^ ^

The operator priority of % is the same as / and higher than +, that means:
1+count % 3 == 1 + (count % 3)
which can never be 0 since modulo returns a value between 0 and 2.

Related

Count how many times can a number be divided by 2

n = int(input())
counter = 0
while n > 0:
if (n // 2) > 1:
counter = counter +1
print (counter)
Hi,
I am a python learner and I am having problems with this homework I was given.
Read a natural number from the input.
Find out how many times in a row this number can be divided by two
(e.g. 80 -> 40 -> 20 -> 10 -> 5, the answer is 4 times)
And I should use while loop to do it.
Any Ideas, because I really don't have any idea how to do it.
This is my best try
You are not changing n. I would write it like this:
while (n % 2) == 0:
n //= 2
counter += 1
Try this, we take the value from "n" and check whether it is divisible by two or not. If it is divisible by two, we increment the counter and then divide that number by 2. If not, it will print the output.
n = int(input("Input your number: "))
counter = 0
while n % 2 != 1:
counter = counter + 1
n = n/2
print(counter)
Your while loop condition is wrong.
While the number is evenly divisible by 2, divide it by 2 and increment counter
num = int(input('Enter a number: '))
counter = 0
while num % 2 == 0 and num != 0:
num = num / 2
counter = counter + 1
print(counter)
The code above will not work as intended. The intended functionality is to take an input natural number and find out how many times in a row the number can be divided by 2. However, the code will only divide the number by 2 once.
To fix this, you can change the code to the following:
n = int(input())
counter = 0
while n > 0:
if (n % 2) == 0:
counter = counter +1
n = n // 2
print (counter)
You need to test whether a number is divisible by 2. You can do this in one of two ways...
x % 2 == 0 # will be True if it's divisible by 2
x & 1 == 0 # will be True if it's divisible by 2
So, you need a loop where you test for divisibility by 2, if True divide your original value by 2 (changing its value) and increment a counter
N = int(input())
counter = 0
if N != 0:
while N % 2 == 0:
counter += 1
N //= 2
print(counter)
Or, if you prefer more esoteric programming, then how about this:
N = int(input())
b = bin(N)
print(0 if (o := b.rfind('1')) < 0 else b[o:].count('0'))

Very Beginner Problem in Python While Loop

Why this While loop is not breaking or stopping
I have added some output screenshot
term = 0
i = 13
while True:
print i > 1
print "i = ",i
if i == 1:
term += 1
break
if i%2 == 0:
i = i / 2
term += 1
if i%2 != 0:
i = i * 3 + 1
term += 1
Output
I also tried This way too
term = 1
i = 13
while i > 1:
print i > 1
if i%2 == 0:
i = i / 2
term += 1
if i%2 != 0:
i = i * 3 + 1
term += 1
Use elif to make the cases mutually exclusive. You don't want multiple if statements to execute in the same loop iteration.
if i%2 == 0:
i = i / 2
term += 1
elif i%2 != 0:
i = i * 3 + 1
term += 1
Or just make it else since the second condition is redundant.
if i%2 == 0:
i = i / 2
term += 1
else:
i = i * 3 + 1
term += 1
The reason it oscillates between 2 and 4 as written is because 2 causes both if statements to run. 2 is even so the first one runs and halves i, making it 1. Now it's odd and the second one triggers, turning 1 into 4.
if i%2 == 0:
i = i / 2 # 2 --> 1
term += 1
if i%2 != 0:
i = i * 3 + 1 # 1 --> 4
term += 1
The next iteration 4 becomes 2.
if i%2 == 0:
i = i / 2 # 4 --> 2
term += 1
These two iterations repeat over and over in an endless cycle.
Let's say your i is 2. It is divisible by 2, so if i % 2 == 0 fires, and i becomes 1. And the code continues to execute, so now we are at if i % 2 != 0 line, and this condition is also true, because you just modified i and it's now 1. So i becomes 4.
Your modified second attempt, which prevents the second condition from being checked if the first one succeeds, is below:
term = 1
i = 13
while i > 1:
print(i > 1)
if i % 2 == 0:
i = i / 2
term += 1
elif i % 2 != 0:
i = i * 3 + 1
term += 1
Also notice that you actually don't need to check the second condition, as it is definitely true if the first one is not, so elif ... line can be replaced just with else:
You can also use continue keyword to stop the rest of the loop from executing if the first condition is true:
term = 1
i = 13
while i > 1:
print(i > 1)
if i % 2 == 0:
i = i / 2
term += 1
continue
if i % 2 != 0:
i = i * 3 + 1
term += 1
Your first attempt has exactly the same problem; fixing it I leave as an exercise for the reader :)
P.S. do not learn Python 2
The problem is:
if i%2 == 0:
i = i / 2
term += 1
if i%2 != 0:
i = i * 3 + 1
term += 1
The problem is that, if i % 2 == 0 is true, it will remain true until i = 1. Once i = 1, i % 2 != 0 executes and makes i = 4.

Finding even numbers with while as

I'm doing this assignment:
Write a program that prints all even numbers less than the input
number using the while loop.
The input format:
The maximum number N that varies from 1 to 200.
The output format:
All even numbers less than N in ascending order. Each number must be
on a separate line.
N = int(input())
i = 0
while 200 >= N >= 1:
i += 1
if i % 2 == 0 and N > i:
print(i)
and its output like:
10 # this is my input
2
4
6
8
but there is an error about time exceed.
The simple code would be:
import math
N = int(input(""))
print("1. " + str(N))
num = 1
while num < math.ceil(N/2):
print (str(num) + ". " + str(num * 2))
num += 1
The problem is that the while loop never stops
while 200 >= N >= 1 In this case because you never change the value of N the condition will always be true. Maybe you can do something more like this:
N = int(input())
if N > 0 and N <= 200:
i = 0
while i < N:
i += 2
print(i)
else
print("The input can only be a number from 1 to 200")

How can I count numbers in the given range?

So I wrote a code which lists all the numbers that are not divisible by 2 and 3. Now I would like to know how many of those numbers are in rage 1000. After googling a bit I haven't found anything that can help me with my case.
Could you guys give me some tips? Would appreciate it!
for i in range(1, 1000):
if i%2 != 0 and i%3 != 0:
print(i)
The range is already defined, put a count
count = 0
for i in range(1, 1000):
if i%2 != 0 and i%3 != 0:
count += 1
print("The number is {}".format(i))
print("Count: {}".format(count))
OUTPUT:
The number is 1
The number is 5
The number is 7
The number is 11
The number is 13
.
.
.
The number is 991
The number is 995
The number is 997
Count: 333
EDIT:
one-liner
print("Count: {}".format(sum(1 for i in range(1000) if i%2 != 0 and i%3 != 0)))
count=0
for i in range(1, 1000):
if i%2 != 0 and i%3 != 0:
count=count+1
print(i)
just make a count inside a IF block
There are 1000/2 = 500 numbers divisible by 2 and 1000/3 = 333 divisible by 3. Among these, the multiples of 6 appear twice and there are 1000/6 = 165 of them.
Hence 1000 - (500 + 333 - 166) = 333.
Up to a billion billion, you would have 1,000,000,000,000,000,000 - (500,000,000,000,000,000 - 333,333,333,333,333,333 - 166,666,666,666,666,666) = 333,333,333,333,333,333 of them, which is just a third.
The simplest solution is to put a count variable in your loop and increment it.
count = 0
for i in range(1, 1000):
if i%2 != 0 and i%3 != 0:
count+=1
print(i)
print(count)
Another solution might be:
count = len([x for x in range(1,1000) if x%2!=0 and x%3!=0])
def number_of_not_divisible(a, b, myrange):
result = 0
least_common_multiple = a * b
while myrange % least_common_multiple != 0:
if myrange % a != 0 and myrange % b != 0:
result += 1
myrange -= 1
partial_result_inside_one_range = 0
for i in range(least_common_multiple):
if i % a != 0 and i % b != 0:
partial_result_inside_one_range += 1
result += partial_result_inside_one_range * (myrange / least_common_multiple)
print(result)
number_of_not_divisible(2, 3, 1000)
You can make it easier and general. You can see that in every interval with size of least common multiple of the two numbers, the number of searched elements are the same. So you just have to count in the first interval, and have to multiple it, and after just count, the numbers in the range%least common multiple. I think it have to work general, but tell me if you get a mistake.

The significance of == 0 in python. (Beginner)

I am very new to coding, I found something very confusing in python for me.
In this small piece of code:
if (count % 4) == 0 and (count % 6) == 0:
print ("Cheesecrackers")
count = count + 1
elif (count % 4) == 0:
print("Cheese")
count = count + 1
elif (count % 6) == 0:
print ("Crackers")
count = count +1
else:
print (count)
count = count + 1
The line: if (count % 4) == 0 and (count % 6) == 0:
Why does the addition of "==0" make a difference to how the code runs?
== 0 means the remainder is zero of the two numbers.
As x % y gives the remainder of x / y, you can say y goes into x evenly if there is no remainder (ie the remainder is 0). However, x % y will not always equal zero. For instance 3 % 2 gives 1. Thus the == 0 is checking that the remainder computed by count % 4 and count % 6 is zero (no remainder)
if (count % 4) == 0:
In the if-else statement, these are conditions or cases that are being tested. So in this case, it is testing if count % 4 has a remainder of 0 (happens when count is perfectly divisible by 4).
If you omitted the '==0', the if statement will just test if the outcome exists regardless of whether it is perfectly divisible or not.
Similarly,
if count:
will also always evaluate to True as long as the variable count exists.

Categories