N的尾随零数

时间:2018-06-29 05:28:38

标签: java factorial

我正在写一种计算给定数字阶乘中尾随零的数量的方法。

  

例如:

     

6! = 720-> 1后退零

     

12! = 479001600-> 2个尾随零

这是我的代码

import java.math.BigInteger;

public class TrailingZeros
{
    public static void main(String[] args)
    {
        int n = 12;
        System.out.println(solution(n));
    }

    public static int solution(int n)
    {
        // computing factorial
        BigInteger result = BigInteger.ONE;
        for (int i = 1; i <= n; i++)
        {
            result = result.multiply(new BigInteger(i + ""));
        }

        String str = String.valueOf(result);
        int count = 0;
        char[] chars = str.toCharArray();

        // counting numbers of trailing zeros
        for (int i = chars.length - 1; i >= 0; i--)
        {
            if (chars[i] != '0')
                break;
            count++;
        }

        return count;
    }
}

工作正常。但是我认为这不是一种有效的算法。请帮忙,谢谢。

3 个答案:

答案 0 :(得分:4)

我认为您当前的方法本身没有任何问题。但是我们实际上可以使用单线来计算尾随零,将原始数字字符串的长度与去除尾随零的数字的长度进行比较:

String input = "479001600";
int numZeroes = input.length() - input.replaceAll("0+$", "").length();
System.out.println(numZeroes);

2

Demo

答案 1 :(得分:1)

即使数字为long,下面的内容仍然有效;

  String string = "479001600";
  int counter = 0;
  while (counter < string.length() && string.charAt(string.length() - 1 - counter) == '0') {
    counter++;
  }
  System.out.println(counter);

// Output will 2

工作演示

here

答案 2 :(得分:1)

您只需要知道因子10在n阶乘中的时间。 10是两个质数的因数:2和5,因此10乘以的次数是2和5出现的最小次数。

怎么样?

public static int solution(int n)
{
    int twos = 0;
    int fives = 0;
    for (int i = 1; i <= n; i++)
    {
        twos += countFactors(i, 2);
        fives += countFactors(i, 5);
    }

    return Math.min(twos, fives);
}

static int countFactors(int n, int fac) {
    int count = 0;
    while (n >= fac && (n%fac) == 0) {
        n /= fac;
        ++count;
    }
    return count;
}

更新:

正如@ david-conrad指出的那样,二位数比五进制要频繁得多,因此我们只需要计算五位数即可:

public static int solution(int n)
{
    int fives = 0;
    for (int i = 1; i <= n; i++)
    {
        fives += countFactors(i, 5);
    }

    return fives;
}

static int countFactors(int n, int fac) {
    int count = 0;
    while (n >= fac && (n%fac) == 0) {
        n /= fac;
        ++count;
    }
    return count;
}

更新2:这是一个演示:http://rextester.com/DWIO77242

相关问题