1

I would like to know how to efficiently divide n terms and sum them up. I have 2 Arrays each containing large Decimal which is stored by an external Library called Apfloat:

Apfloat[] nume=new Apfloat[n]; Apfloat[] deno==new Apfloat[n];

Using a formula, I fill up nume[] with the numerators of some fractions and I fill up deno[] with the denominators of the same fractions. Now I want to find the sum of these fractions. So, at first I just divide each numerator by it's corresponding denominator and add each to a variable sum such that sum=(nume[0]/deno[0])+(nume[1]/deno[1])+(nume[2]/deno[2])... +(nume[n]/deno[n]);

However, that means that I have to divide n times and since dividing huge decimals is a very time consuming process, it cause the program to take a long time to finish.

I then tried finding the LCM of the denominators and multiplying the numerator and denominator by k such that the number * k = LCM. This gave me a single numerator and a single denominator at the end so I only needed to divide 1 time. However, in the process I had to multiply approximately 2n times so, it was slower then the original method which, brings me to my question, Is there a more efficient/faster method to achieve this?

Thanks in advance :)

Paul
  • 670
  • 7
  • 19
  • Can you precompute or cache it? – D. Ben Knoble Dec 01 '15 at 02:45
  • Why not use an `Aprational` array, or two `Apint` ones? There's even an `ApintMath.lcm(Apint a, Apint b)`. – greybeard Dec 01 '15 at 02:52
  • @greybeard Yes, but with the LCM I would still have to multiply many times and ApintMath doesn't support lcm of more then 2 decimals at a time. – Paul Dec 01 '15 at 02:56
  • 1
    suggestion: sum rationals by denominator. I'm disappointed with what little I found documented about `apfloat` (Java as well as C++) - consider using a better documented/more widely known package, none crossing my mind for Java. (`decimals`? A constructive way to think about numbers _if_ conversion from/to human readable representations take more time than computations.) – greybeard Dec 01 '15 at 09:48

0 Answers0