Program crash.

I'am trying to make program for lowest common denominator end when i enter 2 numbers it crashes.. What is wrong in this code? I'am beginner and its 20. Trenning from www.mendo.mk

#include <iostream>

using namespace std;

int main()
{
int br1, br2;
cin >> br1;
cin >> br2;
for(int br3; br3 <= br1*br2; br3++)
{
if((br1%br3) == 0 && (br2%br3) == 0)
{
cout << br3 << endl;
return 0;
}
}
return 0;
}
for(int br3
Undefined behavior, value of br3 is not set.

if((br1%br3) If br3 happens to be 0, you have division by 0.
Can u fix for me :/
Just switch the the modulus operands around and start looping at 1, because 0 % any number is always 0.
for(int br3; br3 <= br1*br2; br3++)
to
for(int br3 = 1; br3 <= br1*br2; br3++)

and

if((br1%br3) == 0 && (br2%br3) == 0)
to
if((br3%br1) == 0 && (br3%br2) == 0)

Also remove the return inside your if loop and replace it with a break. You'll know why if you try a number that's a multiple of itself (eg. 9 81)
Last edited on
Perfect. Now you have division by 0 when br1 is 0 or br2 is 0.
gigo, a denominator cannot be 0
@MiiNiPaa @ThePopivanov
I'm pretty sure you can't find the lowest common multiple of 0 and any number anyway.
You could always implement an if statement to check if one of the numbers is 0, print a message and end the program.
Topic archived. No new replies allowed.