-2

/Here i wrote code for find LCM of two numbers but i don't know why it is not work for 9-10 digit numbers. like if i give input as 245 and 922222222 then it is not work and don't show the output./

//code is given below

#include<iostream>
using namespace std;

long long product;

long long lcm(long long x,long long y){

    if(x>y)
        product=x;
    else
        product=y;

    while(1){
        if(product%x==0 && product%y==0){
            break;
        }
        product++;
    }

    return product;
}

int main(){
    cout<<lcm(245,922222222);
    return 0;
}
Dmitry
  • 13,797
  • 6
  • 32
  • 48

1 Answers1

2

Your code is working fine, it's just going to take a few years for it to finish.

You're wasting a lot of time checking numbers that can't possibly be the result. n % (n + 1) can't possibly be 0 for any n other than 1. In general, n % (n + m) can only be 0 if m is a multiple of n. That means you can add the greater of x and y to product each loop instead of just 1 and cut down on a ton of work:

long long lcm(long long x,long long y) {

    long long greater = std::max(x, y);
    long long product = greater;

    while(product % x != 0 || product % y != 0) {
        product += greater;
    }

    return product;
}

Demo

Of course, even that is more work than you need, since std::gcd exists:

long long lcm(long long x, long long y) {
    return x / std::gcd(x, y) * y;
}

Demo

That may be violating the spirit of the assignment though.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52