How to print multiples of N in a range?

1

The program should receive three N, A, and B values as input, and should print the multiples of N contained in the interval between A and B. I am doing this, but it is going wrong:

N = int(raw_input())
A = int(raw_input())
B = int(raw_input())
x = range(A, B + 1, N)
try:
    for i in range(A, B + 1, N):
        if x == [1]:
            print 'INEXISTENTE'
        else:
            print i 
except:
    if x == [1]:
        print 'INEXISTENTE'

If there are no multiples of N in the given range, the program should print "NONEXISTING". The code works for some values, but for others, such as 3, 5, 9 (N, A, and B, respectively), it does not work. Other code tried:

N = int(raw_input())
A = int(raw_input())
B = int(raw_input())
x = range(A, B + 1, N)
for i in range(A, B + 1, N):
    if i % N == 0:
        print i

It also works for some values and not for others.

Update:

N = int(raw_input())
A = int(raw_input())
B = int(raw_input())
x = range(A, B + 1)

for i in range(A, B + 1):
    if i % N == 0:
        print i
    elif x == []:
        print 'INEXISTENTE'

This last code also does not work. If x does not have values, that is, if there are no multiples in the range, the program should print 'NONEXISTENT' if the entries were, for example, 12, 1 and 10, where there are no multiples of 12 between 1 and 10.

    
asked by anonymous 04.04.2016 / 14:01

4 answers

1

I was able to do this:

N = int(raw_input())
A = int(raw_input())
B = int(raw_input())
for i in range(A, B + 1):
    if i % N == 0:
        print i
if N > B:
    print 'INEXISTENTE' 

Thanks for the tips!

    
04.04.2016 / 21:20
1

In Python there is a pretty cool operator who can help you with this task: % . It returns the rest of the division from one number to the other. Try it out:

>>> 4 % 2
0
>>> 5 % 2
1

In this way, if you want to know if a number is multiple of another, just compare the result of the operation with 0 :

if x % y == 0:
    print('é múltiplo')
else:
    print('não é múltiplo')

So one possible way to do your exercise would be:

n = int(input())
a = int(input())
b = int(input())

for x in range(a, b):
    if x % n == 0:
        print(x)
    else:
        print('Inexistente')

Note: Swap% of% by% with% of range and% by% of% if using Python 2.

    
04.04.2016 / 17:23
0

You need to ensure that the beginning of your range is divisible by N:

A, B, N = [int(raw_input()) for _ in xrange(3)]
multiplos = xrange(A + N - (A % N), B + 1, N)
print '\n'.join(map(str, multiplos)) if len(multiplos) > 0 else 'INEXISTENTE'
    
04.04.2016 / 17:26
-1

Mine has run like this in Python 3:

N = int(input())
A = int(input())
B = int(input())
for i in range(A, B + 1):
    if i % N == 0:
        print (i)
if N > B:
    print ('INEXISTENTE')
    
16.08.2017 / 18:18