0

I am entering two numbers from the user to get the GCD. Error showing at return gcd(a,a%b)

Attach is the code

def gcd(a,b):
   if b==0:
      return a
   return gcd(a,a%b)


a = input("Enter first number: ")
b = input("Enter second number: ")
res = gcd(a,b)
print("GCD of {1} and {2} is {3}".format(a, b,res))
TypeError: not all arguments converted during string formatting
wjandrea
  • 28,235
  • 9
  • 60
  • 81

1 Answers1

0

There are three problems:

  1. The function input() returns a string. So you need to convert the result to a number or integer using int().
  2. The algorithm is wrong. The recursive call should be return gcd(b, a%b).
  3. The positional placeholders in format() are zero based. So the correct placeholders are {0}, {1} and {2}

The fixed code is:

def gcd(a,b):
   if b==0:
       return a
   return gcd(b, a%b)


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
res = gcd(a,b)
print("GCD of {0} and {1} is {2}".format(a, b, res))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Michael Roth
  • 186
  • 6