递归练习6 求出1000的阶乘尾部零的个数(递归)

分析:

5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100...1000    1000 / 5 = 200    5的倍数        1个0  这些数和任意的偶数相乘,结尾就会产生0
5*5 5*5*2 5*5*3 5*5*4 5*5*5 5*5*6 5*5*7 5*5*8 5*5*9 5*5*10...5*5*40       200 / 5 = 40      25的倍数      2个0  第一次将会产生一个零的都统计了,但还有些数会产生两个0,去掉1个0还剩1个0.
5*5*5 5*5*5*2 5*5*5*3 5*5*5*4 5*5*5*5 5*5*5*6 5*5*5*7 5*5*5*8                 40 / 5 = 8        125的倍数    3个0  去掉2个0还剩1个0.
5*5*5*5                                                                                                            8 / 5 = 1        625的倍数    4个0  去掉3个0还剩1个0.
--------------------- 
作者:from_heat 
来源:CSDN 
原文:https://blog.csdn.net/from_heat/article/details/84995275 
版权声明:本文为博主原创文章,转载请附上博文链接!

package com.heima.test;

public class Test7 {
	public static void main(String[] args) {
		System.out.println(fun(1000));
	}

	public static int fun(int num) {
		if(num > 0 && num < 5) {
			return 0;
		}else {
			return num / 5 + fun(num / 5);
		}
	}
}

不用递归方法:

package com.heima.test;

import java.math.BigInteger;

public class Test6 {

	/**
	 * @param args
	 *  需求:求出1000的阶乘所有零和尾部零的个数,不用递归做
	 */
	public static void main(String[] args) {
		/*int result = 1;
		for(int i = 1; i <= 1000; i++) {
			result = result * i;
		}
		
		System.out.println(result);		//因为1000的阶乘远远超出了int的取值范围
		*/
		//demo1();
		demo2();
	}

	public static void demo2() {		//获取1000的阶乘尾部有多少个零
		BigInteger bi1 = new BigInteger("1");
		for(int i = 1; i <= 1000; i++) {
			BigInteger bi2 = new BigInteger(i+"");
			bi1 = bi1.multiply(bi2);	//将bi1与bi2相乘的结果赋值给bi1
		}
		String str = bi1.toString();	//获取字符串表现形式
		StringBuilder sb = new StringBuilder(str);
		str = sb.reverse().toString();	//链式编程
		
		int count = 0;					//定义计数器
		for(int i = 0; i < str.length(); i++) {
			if('0' != str.charAt(i)) {
				break;
			}else {
				count++;
			}
		}
		
		System.out.println(count);
	}

	public static void demo1() {		//求1000的阶乘中所有的零
		BigInteger bi1 = new BigInteger("1");
		for(int i = 1; i <= 1000; i++) {
			BigInteger bi2 = new BigInteger(i+"");
			bi1 = bi1.multiply(bi2);	//将bi1与bi2相乘的结果赋值给bi1
		}
		String str = bi1.toString();	//获取字符串表现形式
		int count = 0;
		for(int i = 0; i < str.length(); i++) {
			if('0' == str.charAt(i)) {	//如果字符串中出现了0字符
				count++;				//计数器加1
			}
		}
		System.out.println(count);
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_40661297/article/details/87888867
今日推荐