JAVA

星期二, 六月 13, 2006

"Lab Hanoi Tower"

package s9325116;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class recursion {
public static void main(String[] args)throws IOException
{ BufferedReader keyboard=new BufferedReader(new InputStreamReader(System.in));
int b=Integer.parseInt(keyboard.readLine());
recursive(b,1,2,3);

}

public static void recursive(int n, int src, int aux, int dst)//(幾個盤子,起點,輔助,終點)
{
if(n==1)
System.out.println("Move 1 from "+src+" to "+ dst);
else
{
recursive(n-1,src, dst, aux);
System.out.println("Move "+n+" from "+src+" to "+dst);
recursive(n-1,aux,src,dst);
}
}
}


---------------------------------------------------------------------------------------------

執行結果

3
Move 1 from 1 to 3
Move 2 from 1 to 2
Move 1 from 3 to 2
Move 3 from 1 to 3
Move 1 from 2 to 1
Move 2 from 2 to 3
Move 1 from 1 to 3

星期一, 六月 12, 2006

Lab Recursive Method

package s9325116;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class recursion {
public static void main(String[] args)throws IOException
{ BufferedReader keyboard=new BufferedReader(new InputStreamReader(System.in));
int b=Integer.parseInt(keyboard.readLine());
int c=recursive(b);
System.out.println(c);
}

public static int recursive(int n)
{
if(n==1)
return 1;
else
return recursive(n-1)+n*n;
}
}

-------------------------------------------------------------------------------------------------

執行結果

222
3671695