利用遞迴 完成405- [hide]import java.util.Scanner;
- public class JPD04 {
- static Scanner keyboard = new Scanner(System.in);
- public static void main(String args[]) {
-
- int n;
- System.out.println("Input the number n:");
- n = keyboard.nextInt();
- System.out.println("Ans:"+sum2(n));
-
- }
- // sum2(1)= 2
- // sum2(n-1)+2*n
- static int sum2(int n)
- {
- if(n ==1)
- {
- return 2;
- }
- else{
- return sum2(n-1)+2*n;
- }
- }
- }
- [/hide]
複製代碼 |