C & C++: This program will figure out the greatest common divisor in two numbers you give.

  • rossiacriiloia / 200 / Wed, 24 Jun 2009 01:40:00 GMT / Comments (0)
  • mambuhl wrote:

    > }
    > printf("The GCD is %d\n", gcd(first, second));here exit(0);
    >}
    >C:>he
    This program will figure out the greatest common
    divisor in two numbers you give.
    Please enter the numbers.
    0
    OK, that's one. Give me another one.
    9
    [crash]
    _____
    C:>he
    This program will figure out the greatest common
    divisor in two numbers you give.
    Please enter the numbers.
    7^Z
    OK, that's one. Give me another one.
    [end]
    _____
    PS: ^Z==EOF
    _________

    #include
    #include

    unsigned
    gcd_my(unsigned a, unsigned b)
    {unsigned t;

    if(a==0 || b==0) return 0;
    while(a != 0)
    {if(a < b)
    {t = a; a = b; b = t;}
    a = a%b;
    }
    return b;
    }

    int main()
    {
    int first, second, nread;
    char input[BUFSIZ];

    printf
    ("This program will figure out the greatest common\n"
    "divisor in two numbers you give.\n");
    printf("Please enter the numbers.\n");
    if (!fgets(input, sizeof input, stdin))
    exit(0);
    if (2!=(nread = sscanf(input, "%d%d", &first, &second)) )
    {
    if (1 != nread || feof(stdin))
    {
    printf("Oh, jeez!\n");
    exit(0);
    }
    printf("OK, that's one. Give me another one.\n");
    if (!fgets(input, sizeof input, stdin))
    goto label;
    if (1 != (nread = sscanf(input, "%d", &second)))
    {
    label:
    printf("You don't want to play? Ok.\n");
    exit(0);
    }
    }
    first = first>=0 ? first: -first;
    second = second>=0 ? second: -second;
    printf("The GCD is %d\n", (int) gcd_my(first, second));
    exit(0);
    }
  • Keywords:

    program, figure, out, greatest, common, divisor, two, numbers, give, c++

  • http://programming.itags.org/c-c++/199417/«« Last Thread - Next Thread »»
  • C & C++ Questions

    • access control?!?

      I feel stupid, because I can't figure out why this shouldn't work.I am getting this error ...

      By vdave420, 1 Comments

    • access control?!?

      I feel stupid, because I can't figure out why this shouldn't work.I am getting this error using MS V...

      By vdave420, 1 Comments

    • Access Control error

      Hello all,Iam trying to read ch from the file and trying to put each word in a variableand the words...

      By anita, 1 Comments

    • Access control and nested classes

      Hi!I'm learning C++ from the book "Thinking in C++". Now I'm reading aboutnested classes and access ...

      By fabiorossi, 5 Comments

    • Access control and nested classes

      Hi!I'm learning C++ from the book "Thinking in C++". Now I'm reading aboutnested classes a...

      By fabio_rossi, 5 Comments