I want to get two numbers as input and calculate all the possible differences in Python

132 views Asked by At

When I give the input as 17, 19: I only get 17, 19, 2 but I expect all numbers below 19 to be given as output. Since we are dealing with primes we should get 1 as GCD.

This is my code:

a=[]
n=int(input("Number of elements in array:"))
for i in range(0,n):
    print(f"Enter number {i+1}: ")
    l=int(input())
    a.append(l)
print(a)


for j in range(len(a)):
    for k in range(len(a)):
        diff = abs(a[j] - a[k])
        if diff > 0 and diff not in a:
            a.append(diff)
       

print (f"The final numbers are: {a}")
    
1

There are 1 answers

0
Flow On

There are a few issues here.

First len(a) in

for j in range(len(a)):
    for k in range(len(a)):
        diff = abs(a[j] - a[k])
        if diff > 0 and diff not in a:
            a.append(diff)

is evaluated once. If you append new elements to a, they will not be considered for further calculations. However you would like to calculate further differences.

Second, you should read about the Euclidean algorithm since it is not working as you are describing it. (Wikipedia for example also includes pseudocode implementations of it). For the difference based version of it (there is also a division based one), you always replace the larger of the two values by their difference: (19, 17) -> (17, 2) -> (15, 2) -> ... -> (3,2) -> (2, 1) -> (1, 1). Therefore the GCD is 1.

The sequence you are looking for thus should be 19, 17, 2, 15, 13, 11, 9, 7, 5, 3, 1.

Also there is no need to ask for the number of elements of the array if you want to recreate that algorithm, since it always needs 2 elements.