1. 程式人生 > >乘方--java遞迴實現--迴圈實現

乘方--java遞迴實現--迴圈實現

1.主程式 

package recursion;

//計算乘方
public class Power {
	static long temp=1;
        //--------遞迴實現乘方計算,時間O(logN)---------
	public long calculate(long x, int y) {
	
		if (y == 1) {
			return x * temp;
		}
		if (y == 2) {
			return (x * x * temp);
		}
		if (y % 2 == 1) {
			temp = x;
		}

		return calculate(x * x, y / 2);

	}

	// ------------遞迴實現乘方,時間O(N)------------------------
	public long calculate2(long x, int y) {
		if (y == 1) {
			return x;
		} else
			return x * calculate2(x, y - 1);
	}
        //--------------迴圈實現乘方,時間O(N)------------------
	public long calculate3(long x, int y) {
		long result = 1;
		for (int i = 0; i < y; i++) {
			result = result * x;
		}
		return result;
	}

}

2.測試程式

import recursion.Power;

public class App {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Power power = new Power();
		long result = power.calculate(5, 10);
		System.err.println(result);
		// ----------------------------
		result = power.calculate2(5, 10);
		System.err.println(result);
		// --------------------
		result = power.calculate3(5, 10);
		System.err.println(result);
	}

}


3.測試結果

9765625
9765625
9765625