14

I was wondering if there was a way to multiply BigInteger variables together, because the * operator cannot be applied to BigInteger.

So I was wondering if it was possible to multiply two BigIntegers together without using the * operator.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
Steffan Harris
  • 9,106
  • 30
  • 75
  • 101
  • Operators only work on objects if it can go through [autoboxing](http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html). The only ones that can do that are the class representations for the primitive types (int -> Integer). –  Jul 29 '13 at 01:12

4 Answers4

24

You use BigIntegers multiply() method like so:

BigInteger int1 = new BigInteger("131224324234234234234313");
BigInteger int2 = new BigInteger("13345663456346435648234313");
BigInteger result =  int1.multiply(int2) 

I should have pointed out a while ago that BigInteger is immutable. So any result of an operation has to be stored into a variable. The operator or operand are never changed.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • If this gets too annoying, you can do work in Groovy which maps the operators correctly. I am implementing some math classes (BigRational for one) and for the first time Java has seemed extremely cumbersome--Although I generally love Java I have to admit that it's not the answer to every programming problem. If you need Java's speed but want advantages like Operator Overloading you might also try Scala. – Bill K Oct 07 '10 at 00:05
  • 1
    In the last snippet line, isn't just "int2" is sufficient as argument passed to multiply? It's a BigInteger after all. – amar Jul 27 '13 at 19:49
  • 1
    @amar Thanks for pointing that out. I'm not sure what I was thinking. Probably a copy-paste error. – jjnguy Jul 29 '13 at 00:42
5

Easier way to implement:

int i = 5;
BigInteger bigInt = new BigInteger("12345678901");
BigInteger result = bigInt.multiply(BigInteger.valueOf(i))
waweru
  • 1,024
  • 14
  • 16
1

You can use the multiply(BigInteger) method in BigInteger. So:

BigInteger result = someBigInt.multiply(anotherBigInt);

BigInteger in Java API

swilliams
  • 326
  • 4
  • 5
0

The result multiplying these specific factors

A: 131224324234234234234313

B: 13345663456346435648234313

Could be this one (I hope I am correct):

R: 1751275668516575787795211751170772134115968581969

Both are considered being two positive integers. And the technique used was Karatsuba’s method

int ab = (mul1) * 10^n + (mul3 - mul1 - mul2) * 10^n/2 + mul2;

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
wolfran
  • 9
  • 1