资源描述
//【习2.22】 用递归算法打印数字塔。
public class Count
{
static void count(int n) //递归方法,输出一行
{
if (n<10)
count(n+1);
System.out.print(" "+n);
}
public static void main(String args[])
{
count(1);
System.out.println();
}
}
/*
程序运行结果如下:
10 9 8 7 6 5 4 3 2 1
*/
//【习2.22】 用递归算法打印数字塔。
public class Tower2
{
final static int M=9;
static void count(int n,int k) //递归方法,输出一行
{
int i;
if (n==1) //在1前留空
for (i=1; i<=M-k; i++)
System.out.print(" ");
System.out.print(" "+n);
if (n<k)
{
count(n+1,k);
System.out.print(" "+n);
}
}
public static void main(String args[])
{
int i;
for (i=1; i<=M; i++)
{
count(1,i);
System.out.println();
}
}
}
/*
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
*/
//【习2.23】 将辗转相除法求两个整数的最大公因数gcd(a,b)用递归方法实现。
public class GCD_recursion
{
public static int gcd(int a,int b) //返回a,b的最大公因数
{
if (b==0)
return a;
if (a<0)
return gcd(-a,b);
if (b<0)
return gcd(a,-b);
return gcd(b, a%b);
}
public static int gcd(int a,int b,int c) //返回a,b,c的最大公因数
{
return gcd(gcd(a,b),c);
}
public static int multiple(int a,int b) //返回a,b的最小公倍数
{
return a*b/gcd(a,b);
}
public static void main(String args[])
{
int a=12,b=18,c=27;
System.out.println("gcd("+a+","+b+")="+gcd(a,b));
System.out.println("gcd("+(-a)+","+b+")="+gcd(-a,b));
System.out.println("gcd("+a+","+b+","+c+")="+gcd(a,b,c));
System.out.println("multiple("+a+","+b+")="+multiple(a,b));
}
}
/*
程序运行结果如下:
gcd(12,18)=6
gcd(-12,18)=6
gcd(12,18,27)=3
multiple(12,18)=36
*/
3
展开阅读全文