Search code examples
pythonpython-3.xindex-error

Nested loop used in hcf finding code in Python returns IndexError:index out of range


I created a program that will generate the HCF(highest common factor) of the given two numbers.

f1 = []
f2 = []
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
n1 = num1 + 1
n2 = num2 + 1
for i in range(1,n1):
      if num1%i == 0: f1.append(i)
for j in range(1,n2):
      if num2%j == 0: f2.append(j)
hcf = 1
for x in range(0,(len(f1)+1) ):
    for y in range(0,(len(f2)+1)):
        if f1[x]==f2[y]:
            hcf = f2[y]
print("The highest common factor of "+str(num1)+" and "+str(num2)+" is "+str(hcf))

It works fine until finding the factors of both the numbers. But when the program was run, it showed an index error at if f1[x]==f2[y]:. the error is:

    if f1[x]==f2[y]:
IndexError: list index out of range

What is the cause of this error and how can I rectify it?


Solution

  • There is no need to have len(f1)+1. Below should work.

    f1 = []
    f2 = []
    num1 = int(input("Enter first number:"))
    num2 = int(input("Enter second number:"))
    n1 = num1 + 1
    n2 = num2 + 1
    for i in range(1,n1):
        if num1%i == 0: f1.append(i)
    for j in range(1,n2):
        if num2%j == 0: f2.append(j)
    hcf = 1
    for x in range(0,(len(f1)) ):
        for y in range(0,(len(f2))):
            print "{0} : {1}".format(x, y)
            if f1[x]==f2[y]:
                hcf = f2[y]
    print("The highest common factor of "+str(num1)+" and "+str(num2)+" is "+str(hcf))