Skip to content

Instantly share code, notes, and snippets.

@peter279k
Created May 24, 2017
Embed
What would you like to do?
TQC+ JAVA
import java.util.Scanner;
public class JPA03 {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
int sum = 1;
System.out.print("Input m:");
int m = keyboard.nextInt();
while(true) {
if(m < 0 || m == 999) {
break;
}
System.out.print("Input n:");
int n = keyboard.nextInt();
System.out.println("Ans (尾端遞迴) : " + factorial(m, n, sum));
System.out.println("Ans (迴圈) : " + factoLoop(m, n));
System.out.print("Input m:");
m = keyboard.nextInt();
}
}
public static int factorial(int m, int n, int sum) {
if(n == 0) {
return sum;
}
return factorial(m, n-1, m * sum);
}
public static int factoLoop(int m, int n) {
int sum = 1;
for(int index=1;index<=n;index++) {
sum *= m;
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment