Home > Net >  Python: count the numbers between a range that are divisible by another integer
Python: count the numbers between a range that are divisible by another integer

Time:06-29

Detail: User enters 3 integers as numX >= numY >= numZ. Count how many integers between the range of numX and numZ that are divisible by numY (while loop required).

This is a practice question from my course worksheet and here are the codes I wrote for which I can't get the correct answer.

print("Enter 3 integer numbers, where as numX ≥ numY ≥ numZ")
x = int(input("numX: "))
y = int(input("numY: "))
z = int(input("numZ: "))

oldx = x
oldy = y
oldz = z
ctr = 0
while x >= y >= z:
    if x % y == 0 or z % y == 0:
        ctr = ctr   1
    x = x - 1
    z = z   1
print(f"There are {ctr} numbers in {oldx}...{oldz} that are divisible by {oldy}")

Thank you in advance for any helpful tips.

CodePudding user response:

You were increasing z value and decreasing x value. You shouldn't do that. If you increase z value then it will not execute between the actual range. You don't even need the old variables.

So, I think the following code snippet will work for you.

Code:

print("Enter 3 integer numbers, where as numX ≥ numY ≥ numZ")
x = int(input("numX: "))
y = int(input("numY: "))
z = int(input("numZ: "))

oldx = x

ctr = 0
while x >= y >= z:
    if x % y == 0:
        ctr  = 1
    x -= 1
print(f"There are {ctr} numbers in {oldx}...{z} that are divisible by {y}")

Output:

Enter 3 integer numbers, where as numX ≥ numY ≥ numZ
numX: 12
numY: 3
numZ: 0
There are 4 numbers in 12...0 that are divisible by 3
  • Related