![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Mar 2005
Posts: 10
Rep Power: 0
![]() |
Greatest common divisor program
The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. Write a recursive function gcd taht returns the greatest common divisor of x and y. The gcd of x and y is defined recursively as follows: If y is equal to 0, then gcd(x,y) is x; otherwise gcd(x,y) is gcd(y,x%y) where % is remainder operator.
#include <stdio.h>
long gcd (int,int);
int main()
{
int x,y,i;
for (i=0; i<=100; i++)
{
printf("Enter 1st integer\n");
scanf("%d",&x);
printf("Enter 2nd integer\n");
scanf("%d",&y);
}
return 0;
}
long gcd (int x,int y)
{
if (y)
{
return gcd(y, x%y);
}
else
{
return x;
}
return 0;
}prblem im having is that it keeps on asking me to enter 1st integer and 2nd integers Last edited by strider496; Mar 23rd, 2005 at 4:07 PM. |
|
|
|
|
|
#2 |
|
Professional Programmer
|
*EDIT* It's a function you're writing. I promise to read it completely from now on :o */EDIT*
The loop will continue to run as long as the conditions are being met. To test it, add a printf to see if the results are correct.
__________________
Amateurs built the ark Professionals built the Titanic Last edited by peace_of_mind; Mar 23rd, 2005 at 1:28 PM. |
|
|
|
|
|
#3 |
|
Newbie
Join Date: Mar 2005
Posts: 10
Rep Power: 0
![]() |
revise prog
#include <stdio.h>
int gcd(int a, int b);
int main()
{
int x, y, z;
int gcd(int, int);
printf("Enter 1st integer\n");
scanf("%d",&x);
printf("Enter 2nd integer\n");
scanf("%d",&y);
if(y==0)
{
z = gcd(x, y);
printf("gcd(%d,%d) is %d\n" x,y,z ;}
else
printf("gcd(%d,%d is gcd(%d, %d %% %d)\n",x,y,x,x%y);
}
int gcd(int a, int b)
{
while (a != b){
if (a > b)
a -= b;
else
b -= a;
}
return a;
} |
|
|
|
|
|
#4 |
|
Programmer
Join Date: Feb 2005
Posts: 64
Rep Power: 4
![]() |
Your first post was correct you just never called the function.
You new gcd function is not recursive. A recursive function is a function that calls itself. #include <stdio.h>
long gcd (int,int);
int main()
{
int x,y,i,z;
printf("Enter 1st integer\n");
scanf("%d",&x);
printf("Enter 2nd integer\n");
scanf("%d",&y);
z = gcd(x,y);
printf("gcd is %d\n", z);
return 0;
}
long gcd (int x,int y)
{
if (y) {
return gcd(y, x%y);
}else {
return x;
}
} |
|
|
|
|
|
#5 |
|
Newbie
Join Date: Mar 2005
Posts: 10
Rep Power: 0
![]() |
thx guys got my programs to run
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|