Print in ascending order the first natural n's that are multiples of i or j or both

2

Given n and two positive integers i and j other than 0, print in ascending order the first natural n's that are multiples of i or or both.

Example: For n = 6, i = 2 and j = 3 the output should be: 0,2,3,4,6,8.

n = int(input("Digite n: "))

i = int(input("Digite i: "))

j = int(input("Digite j: "))

lista = []

for k in range(i,i+1):
    for l in range(0,n):
        print("{}*{} = {}".format(k,l,k*l))
        lista.append(k*l)



for k in range(j,j+1):
    for l in range(0,n):
        print("{}*{} = {}".format(k,l,k*l))
        lista.append(k*l)


print(lista)

The above program with n = 6, i = 2 and j = 3 is output:

[0, 2, 4, 6, 8, 10, 0, 3, 6, 9, 12, 15]

For the output to be correct, I would need to sort the above list in ascending order, excluding duplicate values:

[0.2,3,4,6,8,9,10,12,15]

and then get the first 6 values, getting: [0,2,3,4,6,8], which is the expected output.

Any ideas how to improve / correct the above program?

    
asked by anonymous 23.03.2018 / 03:55

1 answer

4

If you only need a list with n numbers why does the overload add more then unnecessarily remove them?

You can use a while loop and the module to see if any of the nums i and j is multiple of each number:

n = 6
i = 2
j = 3

nat_nums, x = [], 0
while len(nat_nums) < n: # enquanto a a nossa lista tiver menos que 'n' elementos
    if(x%i == 0 or x%j == 0): # modulo para ver se e multiplo de algum ou ambos
        nat_nums.append(x) # adicionar 'x' a nossa lista
    x += 1

print(nat_nums) # [0, 2, 3, 4, 6, 8]

STATEMENT

Using a function and a generator :

def get_multis(n, i, j):
    x = 0
    while n > 0:
        if(x%i == 0 or x%j == 0): # modulo para ver se e multiplo de algum ou ambos
            yield x
            n -= 1
        x += 1

n, i, j = 6, 2, 3
print(list(get_multis(n, i, j))) # [0, 2, 3, 4, 6, 8]

DEMONSTRATION

PS: this way it's already neat.

    
23.03.2018 / 08:41