Home » Category » C & C++

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

200| Mon, 12 May 2008 15:15:00 GMT| rossiacriiloia| 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 & Tags: program, figure, out, greatest, common, divisor, two, numbers, give, c++

URL: http://programming.itags.org/c-c++/199417/
 
«« Prev - Next »» 0 helpful answers below.

C & C++ Hot Answers

C & C++ New questions

C & C++ Related Categories