2

First off, I know there are many different easier/reliable ways to perform what I am about to ask, but that is not the point of my question.

I am attempting to compare two sets of integers as if they were fractions. What I mean by this is suppose I have a 2d array:

int array[2][2];

array[0][0] = 2;
array[0][1] = 3;
array[1][0] = 1;
array[1][1] = 50;

How I want to treat these numbers is that the number in:

array[0][0] = 2 <--- is the numerator

array[0][1] = 3 <--- is the denominator

Or just 2/3 in this case. What I want to do is then compare the two fractions;

if(2/3 < 1/50){
  //blah blah blah code here
}

The caveat here is that I can not convert the numbers to floating point numbers to retain their accuracy or create a temporary floating point placeholder. Is there any way to compare these using only integer values?

I also don't know exactly what I should tag for this question, if you think of something let me know and I'll tag it.

Jim Balter
  • 16,163
  • 3
  • 43
  • 66
Jason M.
  • 692
  • 2
  • 8
  • 24

3 Answers3

5

Cross multiply the two numerators by one another's denominators

IE

2/3 vs 1/50th: multiply 50 and 1 by 3 and multiply 2 and 3 by 50.

Then you can compare the numerator without having to convert to a float.

argentage
  • 2,758
  • 1
  • 19
  • 28
  • The example is correct but the wording in the first sentence is not. Should be "cross multiply the two fractions by one another's denominators". – Jon Burgess Jun 28 '12 at 04:18
  • very nice, creating a common denominator didn't even cross my mind, thanks! – Jason M. Jun 28 '12 at 04:26
1
if(array[0][0]*array[1][1])<array[0][1]*array[1][0])
{
    // your code here

}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Y2theZ
  • 10,162
  • 38
  • 131
  • 200
0

The most straightforward way is to find the least common multiple, and then convert the numerator. After that you could compare the numerator as integers.

i.e. 2*50 = 100; 1 * 3 = 3; ==> 100 > 3

Hao Liu
  • 122
  • 3
  • Least common multiple? No, you just multiply them. – flight Jun 28 '12 at 04:21
  • For the example asked, I simply multiply them. But the array could be more than 2 rows, it has to given a more generic solution. [2,3][1,50][1,25] ==> [100,150][3,150][6,150], 150 is the least common multiple for 3, 50, 25. – Hao Liu Jun 28 '12 at 04:34