Potenzfunktion

PPhilipp

Grünschnabel
Es soll eine Funktion implementiert werden

public static BigInteger power1 (BigInteger b, BigInteger e)

welche für alle e>= 0 die Potenz b^e berechnet, indem in einer Schleife b*b*...*b bestimmt wird.


Dann soll eine rekursive und eine iterative Version geschrieben werden, welche nur O(log e) Multiplikationen benötigt.
 
Servus!

Code:
	private BigInteger power1(BigInteger b1, BigInteger b2) {
		BigInteger result = null;
		if (b1.equals(BigInteger.ZERO) || b2.longValue() < 0)
			return null;
		if (b2.equals(BigInteger.ZERO))
			return BigInteger.ONE;
		if (b1.equals(BigInteger.ONE))
			return BigInteger.ONE;
		if (b2.equals(BigInteger.ONE))
			return b1;
		result = b1;
		for (long i = 1l; i < b2.longValue(); i++) {
			result = result.multiply(b1);
		}
		return result;

	}

Gruß Tom
 

Neue Beiträge

Zurück