0

Here is the instructions to my code and my code, I am receiving type error:

The greatest common divisor (GCD) of two integers is the largest integer that will evenly divide both integers. Write a program, with comments, that asks the user to input two positive integers and calculates the corresponding GCD. You may assume the user will input valid numbers. Display a suitable message showing the 2 integers and their GCD.

Steps for calculating the GCD is given below.

  • set a = to the larger integer and b = the smaller integer (if they are different)
  • while b≠0 perform the following steps:
  • rem = remainder obtained after dividing a by b
  • set a = to the current value of b
  • set b = rem (as calculated in step 2a)
  • gcd = value of a (i.e. previous value of b) after exiting the while loop.

A sample session showing user inputs and corresponding outputs is given below.

image output

def gcd(a, b):
    if b > a:
        return gcd(b, a)
    if a % b == 0:
        return b
    return gcd(b, a % b)       
a=input('Enter first positive Integer :');
b=input('Enter second positive Integer :');
s = 'The gcd of ' + repr(a) + ' and ' + repr(b) + ' is ' +repr(gcd(a, b))
print(s)
4
  • 2
    Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! See also: How to Ask Commented Mar 29, 2017 at 3:07
  • 1
    Try to write self-contained questions. Here, instead of prompts for data, you could just run a test with known numbers and test for the desired response. In fact, "test first" where you have tests for the function before you even write it, is a good discipline and helpful here on SO. Commented Mar 29, 2017 at 3:28
  • Note that the test for b > a is unnecessary; if b is bigger on the first iteration, the first recursive call reverses the two values anyway. Commented Mar 29, 2017 at 4:35
  • 1
    You should show us where the error occurs. It's not clear what the issue is you're having. Commented Mar 29, 2017 at 9:39

1 Answer 1

1

You're getting a TypeError because the input function treats all inputs as strings. You need to convert the input to an integer before trying to perform the gcd function on it. e.g.:

def gcd(a, b):
    a = int(a)
    b = int(b)
    if b > a:
        return gcd(b, a)
    if a % b == 0:
        return b
    return gcd(b, a % b)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.