hi guys, i have a problem when i insert two numbers that are negative , the answer is zero. i know that no matter if its negative, it is always positve LCD.
here is little part of my code:
int leastCommonDenominator(int a, int b)
{
int c;
c = (a > b) ? a : b;
do {
if (c % a == 0 && c % b == 0)
{
return c;
}
else
{
c++;
}
} while (true);
please show me in my code what to fix, im not good at C++ and some of its logic. Thank you.
#include <iostream>
#include <cmath>
int main()
{
int num1{ 0 };
int num2{ 0 };
std::cout << "Enter two negative numbers and I will tell you the absolute value:\n";
std::cin >> num1 >> num2;
std::cout << "Number 1 value is " << std::abs(num1) << std::endl;
std::cout << "Number 2 value is " << std::abs(num2) << std::endl;
return 0;
}
@chicofeo I used this as a template to do the code , but I tried , and don't know how to do it still. Can you show me how to implement it to my code or anyone for that matter? Hope
For a reply and thank you
The point is that if a or b is negative, you should take it's absolute value to make it positive. Then compute the LCD of the resulting two positive numbers.
Once you get your code working, try looking up other algorithms for the the LCD. There are faster ways to do it.
Although the sign of a and b is irrelevant as far as the LCD is concerned, most of the algorithms to find it are premised on a and b being positive, so best to start with expressions like
a = abs( a );
b = abs( b );
in your function to ensure this. You will need header <cstdlib> for ints. (Header <cmath> overloads this for doubles).
I would guess from the "common denominator" in your title that you are after the least common multiple (LCM) of a and b. A common multiple of both a and b is a * b. However, this will contain all their common factors exactly twice. Hence, the LCM for positive a and b is
LCM(a,b) = a * b / HCF(a,b)
where HCF is the "highest common factor" (aka "greatest common divisor" or GCD). This can be solved by a very standard and easily-coded algorithm (google "Euclid's algorithm").
So:
- in your LCD/LCM function, call abs() to make a and b positive;
- write a separate function to calculate the HCF (aka GCD);
- in your LCD/LCM function return a * b / HCF(a,b)