Multiples

Does anyone have, or know where I could get a snippet of a function that accepts four integer values (two numerators and two denominators) and finds the least common denominator, solves and returns the solved fraction as two integers (a numerator and denominator)???

Thanks in advance for any help.
Just for a gues, do you mean you have like you have 1, 3, 2, 5, wich says you want to add 1/3 with 2/5 which is 8/15, and then your function returns 15?
Last edited on
That would be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void lcd(int a1, int a2, int b1, int b2, int& result1, int& result2) 
{
    //Calculate the result:
    result1 = a1 * b1;
    result2 = a2 * b2;

    //find out wich number is smaller
    int smallest = result1;
    if (result2 < result1)
        smallest = result2;

    //Make the numerator and denominator as small as possible:
    for (unsigned int i = 0; i < smallest; i++)
    {
        if (result1 % i == 0 && result2 % i == 0)
        {
            result1 /= i;
            result2 /= i;
        }
    }
}


I don't know if there's an more efficient way but it should work. Also, you might want to make result1 and result2 of type __int64 to hold large data, since (2^31-1)*(2^31-1) is almost 2^62. But it is just to give you an idea.
Last edited on
Look up LCM or GCD on Wikipedia. There is a simple algorithm and code posted there.
magnificence7 , 1/3 + 2/5 = 11/15 not 8/15

my code does whole numbers and fractions (1 1/3)
it also base on a 3 part array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>

void Reduce ( int *rout );
void PrintFraction ( int *out );

void AddFraction ( int *fa , int *fb , int *out )
{
	out[1] = (fa[1] * fb[2]) + (fa[2] * fb[1]);
	out[2] = fa[2] * fb[2];	
	out[0] = fa[0] + fb[0];
	Reduce ( out );
}

void Reduce ( int *rout )
{
	int sum = 0, val = 0;
	if (rout[1] >= rout[2])
	{
		sum = rout[1]/rout[2];
		rout[0] += sum;
		rout[1] -= (rout[2] * sum);
	}
	
	for ( sum = rout[1]; sum > 1; sum --)
	{
		if ( rout[1] % sum == 0 && rout[2] % sum == 0 )
		{
			val = sum;
			break;
		}
	}
	
	if (val > 1)
	{
		rout[1] = rout[1] / val;
		rout[2] = rout[2] / val;
	}
}

void PrintFraction ( int *out )
{
	std::cout << out[0] << " " << out[1] << "/" << out[2] << std::endl;
}

int main()
{
	int fractiona[3] = { 0 , 1 , 3 };
	int fractionb[3] = { 0 , 2 , 5 };
	int result[3] = { 0 , 0 , 0 };
	int test[3] = { 0 , 9 , 33 };
	int test2[3] = { 0 , 10 , 25 };
	
	AddFraction( fractiona , fractionb , result );
	PrintFraction ( result );
	Reduce( test );
	PrintFraction ( test );
	Reduce( test2 );
	PrintFraction ( test2 );
	return 0;
}
yeah, my bad.
Sorry it took so long to reply but thanks you guys sooooo much!!! Helped a ton
Topic archived. No new replies allowed.