- import java.util.Scanner;
- public class JPA04 {
- static Scanner keyboard = new Scanner(System.in);
- public static void main(String args[]) {
- int m,n;
- System.out.print("Input m: ");
- m=keyboard.nextInt();
- while(m!=999)//排除999
- {
- System.out.print("Input n: ");
- n=keyboard.nextInt();
- System.out.println("Ans (尾端遞迴): "+powerTail(m,n,1/*1是r初始值*/))/*呼叫函式powerTail*/;
- System.out.println("Ans (迴圈): "+powerLoop(m,n,1/*1是r初始值*/))/*呼叫函式powerLoop*/;
- System.out.print("Input m: ");
- m=keyboard.nextInt();
- }
- }
- static int powerTail(int m, int n, int r)
- {
- if(n==0)/*當遞減至0,馬上回傳r*/
- return r;
- else
- return powerTail(m, n-1, r*m);
- }
- /*
- powerTail(2,3(n),1(r))
- =powerTail(2,2(n-1),2(r*m))
- =powerTail(2,1((n-1)-1),2*2((r*m)*m))
- =powerTail(2,0(((n-1)-1)-1),2*2*2(((r*m)*m))*m) n變0,馬上回傳r(r=((r*m)*m))*m)
- =2*2*2
- */
- static int powerLoop(int m, int n, int r)
- {
- while(n!=0)//當n遞減至0,才回傳r
- {
- r*=m;
- n--;
- }
- return r;
- }
- /*
- powerLoop(2,3(n),1(r))
- =powerLoop(2,2(n-1),2(r*m))
- =powerLoop(2,1((n-1)-1),2*2((r*m)*m))
- =powerLoop(2,0(((n-1)-1)-1),2*2*2(((r*m)*m))*m) n變0,馬上回傳r(r=((r*m)*m))*m)
- =2*2*2
- */
- }
複製代碼 |