Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

least common multiple

Name: Anonymous 2011-12-02 18:26

Can you help me write a least common multiple program in C++ ?

Name: Anonymous 2011-12-02 19:23

nig

Name: Anonymous 2011-12-02 19:28


// BRUTAL FORCE SOLUTION!!!
int lcm(int a, int b)
{
  int i = 0;
  while 1
  {
     ++i;
     if(i % a == 0 && i % b == 0) {
       return i;
     }
  }
}

Name: Anonymous 2011-12-02 19:52

Use Euclids for gcd, then use n*m/gcd

Name: Anonymous 2011-12-02 19:56

int gcd(int a, int b) { if(b == 0) return a; else return gcd(b, a % b);
int lcm(int a, int b) { return (a * b) / gcd(a, b); }

Name: Anonymous 2011-12-02 20:22

that brutal force solution was really good actually.

Name: Anonymous 2011-12-03 8:40

>>6
made me smile

Name: Anonymous 2011-12-03 17:54

>>5

you guys should do:


int lcm(int a, int b) { return (a / gcd(a, b)) * b; }


to be immune to overflow, unless the lcm of a and b happens to be larger than the maximum int.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List