Home > Blockchain >  Python Program to Print all Numbers in a Range Divisible by a Given Number
Python Program to Print all Numbers in a Range Divisible by a Given Number

Time:11-13

Python Program to Print all Numbers in a Range Divisible by a Given Numbers L=int(input()) #L=[2,4,5] take all input at a time to process with range number divisible with give inputs those numbers print output is 20,40 bcuz of 2,4,5 divisible 20, 40 only

L=int(input)) for i in l: for j in range(1,50): if j%i==0: print(j)

I want out put 20,40

Range divisible with all list l

CodePudding user response:

I'm not sure quite sure what you're asking, but I think the gist of it is that you want to print all numbers in a given range that are divisible by a list.

In that case, there is no need to do a type coercion to int on your list, I'm not sure why you did that.

my_list = [2, 4, 5]

# create an empty output list
output = []
# iterate through a range.
for i in range(1, 50):
    # create a boolean array that checks if the remainder is 0 for each 
    # element in my_list
    if all([i % j == 0 for j in my_list]):
        # if all statements in the boolean list created above are true 
        # (number is divisible by all elements in my_list), append to output list
        output.append(i)

print(output)

CodePudding user response:

First you need to calculate the least common multiple (lcm) of the numbers in the list. In this case is 20. At this point you know that every integer number that you multiply by 20 is going to be divisible by all the numbers in the list (2 * 20=40, 3 * 20=60 ...). So for a range you must divide the maximum range number (in your case 50) and truncate the result. 50/20 is 2.5 so you truncate to 2. Make a loop and multiply from 1 to n (n=2 in this case) and multiply it by 20. So 20 * 1 is 20 and 20* 2 is 40. This is the result. If the lower range number is not 1 then check if the result is == or > to this lower number (20 > 1 and 40 > 1, no problem!).

  • Related