Idea is to use two java threads, one thread calculates base1 ^ power1 using BigInteger and another thread calculates base2 ^ power2. Use thread.join() to wait for both thread to complete and sum result from both thread.
package com.dw.thread;
import java.math.BigInteger;
public class ComplexCalculation {
public BigInteger calculateResult(BigInteger base1, BigInteger power1, BigInteger base2, BigInteger power2) throws InterruptedException {
BigInteger result;
/*
Calculate result = ( base1 ^ power1 ) + (base2 ^ power2).
Where each calculation in (..) is calculated on a different thread
*/
PowerCalculatingThread thread1 = new PowerCalculatingThread(base1, power1);
PowerCalculatingThread thread2 = new PowerCalculatingThread(base2, power2);
thread1.start();
thread2.start();
thread1.join(); // important: wait thread to complete
thread2.join();
result = thread1.getResult().add(thread2.getResult()); // add two result
return result;
}
private static class PowerCalculatingThread extends Thread {
private BigInteger result = BigInteger.ONE;
private BigInteger base;
private BigInteger power;
public PowerCalculatingThread(BigInteger base, BigInteger power) {
this.base = base;
this.power = power;
}
@Override
public void run() {
/*
Implement the calculation of result = base ^ power
*/
for (BigInteger i = BigInteger.ZERO; i.compareTo(power) != 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(base);
}
}
public BigInteger getResult() { return result; }
}
public static void main(String[] args) throws InterruptedException {
ComplexCalculation c = new ComplexCalculation();
BigInteger result = c.calculateResult(new BigInteger("123"), new BigInteger("10"), new BigInteger("456"), new BigInteger("20"));
System.out.println(result);
}
}