java - Calculating the product of BigInteger[] -


context: i'm trying calculate factorials large n using biginteger class in java (for n>100,000) , far i'm doing:

  • produce primes less or equal n using sieve of erasthones

  • find powers raised.

  • raise numbers respective powers.

  • use divide , conquer recursive method multiply them all.

from research i've done on internet, asymptotically faster multiplying k n. i've noticed slowest part of implementation part multiply prime powers. questions are:

  • is there faster way calculate product of lots of numbers?
  • can implementation improved ?

code:

public static biginteger product(biginteger[] numbers) {     if (numbers.length == 0)         throw new arithmeticexception("there nothing multiply!");     if (numbers.length == 1)         return numbers[0];     if (numbers.length == 2)         return numbers[0].multiply(numbers[1]);      biginteger[] part1 = new biginteger[numbers.length / 2];     biginteger[] part2 = new biginteger[numbers.length - numbers.length / 2];     system.arraycopy(numbers, 0, part1, 0, numbers.length / 2);     system.arraycopy(numbers, numbers.length / 2, part2, 0, numbers.length - numbers.length / 2);      return product(part1).multiply(product(part2)); } 
  • note biginteger uses karatsuba algorithm multiplication.
  • i know there lots of questions calculating factorials. mine calculating product of bigintegers there not resource. (i've seen "use divide , conquer method", don't remember where, , haven't seen implementation around.

one way improve performance following:

  1. sort array of numbers need multiply together
  2. create 2 new lists: a , b.
  3. for each number in input list need multiply, appear more once. let's number v_i appears n_i times. add v_i a n_i / 2 times (rounded down). if n_i odd, add v_i once b well.
  4. to compute result, do:
biginteger = product(a); biginteger b = prudoct(b); return a.multiply(a).multiply(b); 

to see how works, consider input array [2, 2, 2, 2, 3, 3, 3]. so, there 4 2s , 3 3s. arrays a , b correspondingly be

a = [2, 2, 3] b = [3] 

then recursively call compute product of these. note reduced number of numbers want multiply 7 4, factor of two. trick here numbers occur many times, can compute product of half of them, , raise power of two. similar how power of number can computed in o(log n) time.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -