jackspa's Avatar, Join Date: Feb 2009
Go4Expert Member
For lcm try this one:
int lcm(int a,int b)
{
int n;
if(a<b)
{
n=a;
a=b;
b=n;
}
for(n=a;n%b!=0;n+=a)
return n;
}
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
After 8 posts I would have thought you would know about code blocks by now. USE THEM PLEASE.
jackspa's Avatar, Join Date: Feb 2009
Go4Expert Member
For lcm try this one:
Code:
int lcm(int a;int b)
{
             int n;
             if(a<b)
             {
                         n=a;
                         a=b;
                         b=n;      
             }
             for(n=a;n%b!=0;n+=a)
                  return n;
}
jackspa's Avatar, Join Date: Feb 2009
Go4Expert Member
i had written that function using blocks.i don't know what happened when i posted it.
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Added that for you now.
jackspa's Avatar, Join Date: Feb 2009
Go4Expert Member
thank you.
Zaiber's Avatar, Join Date: Dec 2009
Newbie Member
Actually, I used the code on the first page to correct my code 'til I got it right. Needed this for a take home exam for C class.

Thanks, and in return I'll give you my code which might help someone.

Code:
int gcd( int x, int y) {
         if ( y == 0 ) {
         return x;
         }
          else if (x%y == 0) {
          return y;
          }
          else {
           return gcd(y,x%y);
          }
          }
COKEDUDE's Avatar, Join Date: Feb 2010
Newbie Member
Wouldn't this code also cover both cases of GCD whether your first variable is bigger or your second variable is bigger?

Code:
void gcd(int x, int y)
{
    if (x > y)
    {
        int c;
        while(1)
        {
            c = x % y;
            return y;
            x = y;
            y = c;
        }
    if (y > x)
    {
        int d;
        while(1)
        {
            d = x % y;
            return x;
            y = x;
            x = d;
        }

    }
}
Zaiber's Avatar, Join Date: Dec 2009
Newbie Member
Quote:
Originally Posted by COKEDUDE View Post
Wouldn't this code also cover both cases of GCD whether your first variable is bigger or your second variable is bigger?

Code:
void gcd(int x, int y)
{
    if (x > y)
    {
        int c;
        while(1)
        {
            c = x % y;
            return y;
            x = y;
            y = c;
        }
    if (y > x)
    {
        int d;
        while(1)
        {
            d = x % y;
            return x;
            y = x;
            x = d;
        }

    }
}
Mine worked for both instances ok.
COKEDUDE's Avatar, Join Date: Feb 2010
Newbie Member
Quote:
Originally Posted by Zaiber View Post
Mine worked for both instances ok.
Wow your code is so much simpler and easier to use . Thx for the code. I'm just stubborn about making up my own stuff sometimes.