快速求解冪運算-連續平方
阿新 • • 發佈:2018-12-11
1.冪運算可以使用連續平方的方法來解決,但是求得結果只能是2的整數次方那麼剩下的冪指數的求解通過遞迴來解決,使用具體的程式碼如下:
import java.util.Scanner; public class 快速冪運算_平方求解{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); long x = sc.nextLong(); long n = sc.nextLong(); long res = exp(x,n); System.out.println(res); } private static long exp(long x, long n) { if(n==0){ return 1; } int count = 2; long temp = x; while(count <= n){ temp = temp * temp; count *= 2; } long res = exp(x, n - count / 2); res = temp * res; return res; } }