xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

LeetCode 阶乘后的零算法题解 All In One

LeetCode 阶乘后的零算法题解 All In One

factorial

阶乘后的零原理 图解

  1. 实现 factorial
  2. 计算后面 0 的个数,除 0! 本身的 0

阶乘!

那么 "0!" 是多少?
零的阶乘很有趣……一般惯例都是 0! = 1

有趣的是,我们没有把任何数相乘,但常规是零的阶乘等于一,这也会简化很多方程式。

https://www.shuxuele.com/numbers/factorial.html
https://www.shuxuele.com/definitions/factorial.html

脑筋急转弯

  1. 数学题解

n!n! 尾零的数量即为 n!n! 中因子 1010 的个数,而 10=2\times 510=2×5,因此转换成求 n!n! 中质因子 22 的个数和质因子 55 的个数的较小值。

由于质因子 55 的个数不会大于质因子 22 的个数(具体证明见方法二),我们可以仅考虑质因子 55 的个数。

而 n!n! 中质因子 55 的个数等于 [1,n][1,n] 的每个数的质因子 55 的个数之和,我们可以通过遍历 [1,n][1,n] 的所有 55 的倍数求出。


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-10-07
 * @modified
 *
 * @description 172. Factorial Trailing Zeroes
 * @description 172. 阶乘后的零
 * @difficulty Medium
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/factorial-trailing-zeroes/
 * @link https://leetcode.cn/problems/actorial-trailing-zeroes/
 * @solutions
 *
 * @best_solutions
 *
 */

export {};

const log = console.log;

// 0 <= n <= 104

var trailingZeroes = function(n) {
    let ans = 0;
    for (let i = 5; i <= n; i += 5) {
        for (let x = i; x % 5 === 0; x /= 5) {
            ++ans;
        }
    }
    return ans;
};


  1. 优化计算, 因此我们可以通过不断将 nn 除以 55,并累加每次除后的 nn,来得到答案。

var trailingZeroes = function(n) {
    let ans = 0;
    while (n !== 0) {
        n = Math.floor(n / 5);
        ans += n;
    }
    return ans;
};

https://leetcode.cn/problems/factorial-trailing-zeroes/solution/jie-cheng-hou-de-ling-by-leetcode-soluti-1egk/

172. 阶乘后的零

  1. Factorial Trailing Zeroes


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-10-07
 * @modified
 *
 * @description 172. Factorial Trailing Zeroes
 * @description 172. 阶乘后的零
 * @difficulty Medium
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/factorial-trailing-zeroes/
 * @link https://leetcode.cn/problems/actorial-trailing-zeroes/
 * @solutions
 *
 * @best_solutions
 *
 */

// export {};

const log = console.log;

// 0 <= n <= 104
function trailingZeroes(n: number): number {
  let num: number = 0;
  for (let i = 5; i <= n; i += 5) {
    for (let j = i; j % 5 === 0; j /= 5) {
      // ++num;
      // num++;
      num += 1;
    }
  }
  return num;
};

// function trailingZeroes(n: number): number {
//   if(n === 0) return 1;
//   function factorial(n, multi = 1) {
//     if(n === 1) return multi;
//     multi *= n;
//     return factorial(n - 1, multi)
//   }
//   const num = factorial(n);
//   const arr:string[] = `${num}`.split(``).reverse();
//   let len: number = 0;
//   for(const item of arr) {
//     if(item === '0') {
//       len += 1;
//     } else {
//       break;
//     }
//   }
//   return len;
// };


// 大数相乘 ???

// testCase factorial(30) = 2.652528598121911e+32 ❌
// 通过测试用例:21 / 500
// 输入:30 输出:0 预期结果:7

/* 

(() => {
  const log = console.log;
  function factorial(n, multi = 1) {
    if(n === 0) {
      return 1;
    }
    if(n === 1) {
      return multi;
    }
    multi = n * multi;
    return factorial(n - 1, multi);
  };

  const arr = [...new Uint8Array(100)].map((item, i) => i);
  // for (const [item, i] of arr.entries()) {
  //   log(`item, i =`, item, i);
  // }
  for (const item of arr) {
    log(`testCase factorial(${item}) =`, factorial(item));
    if(`${factorial(item)}`.includes(`e`)) {
      break;
    }
  }
  // factorial(50)
  // 3.0414093201713376e+64
  // 阶乘, `科学计数法` `e` bug ❌
})();

*/


/*

$ npx ts-node ./172\ factorial-trailing-zeroes.ts

testCase factorial(0) = 1
testCase factorial(1) = 1
testCase factorial(2) = 2
testCase factorial(3) = 6
testCase factorial(4) = 24
testCase factorial(5) = 120
testCase factorial(6) = 720
testCase factorial(7) = 5040
testCase factorial(8) = 40320
testCase factorial(9) = 362880
testCase factorial(10) = 3628800
testCase factorial(11) = 39916800
testCase factorial(12) = 479001600
testCase factorial(13) = 6227020800
testCase factorial(14) = 87178291200
testCase factorial(15) = 1307674368000
testCase factorial(16) = 20922789888000
testCase factorial(17) = 355687428096000
testCase factorial(18) = 6402373705728000
testCase factorial(19) = 121645100408832000
testCase factorial(20) = 2432902008176640000
testCase factorial(21) = 51090942171709440000
testCase factorial(22) = 1.1240007277776077e+21

*/

// 测试用例 test cases
const testCases = [
  {
    input: 3,
    result: 0,
    desc: 'value equal to 0',
  },
  {
    input: 30,
    result: 7,
    desc: 'value equal to 7',
  },
];

for (const [i, testCase] of testCases.entries()) {
  const result = trailingZeroes(testCase.input);
  log(`test case ${i} result: `, result === testCase.result ? `✅ passed` : `❌ failed`, result);
}

LeetCode 题解 / LeetCode Solutions

https://www.youtube.com/channel/UCftIXZeipv4MTVwmfFphtYw/videos

YouTube & LeetCode 力扣官方算法题解视频列表

https://www.youtube.com/playlist?list=PLamwFu9yMruCBtS2tHUD77oI_Wsce-syE

https://github.com/xgqfrms/leetcode/issues/14

https://www.youtube.com/results?search_query=+Leetcode+172

https://neetcode.io/

https://github.com/neetcode-gh/leetcode/blob/main/javascript/172-Factorial-Trailing-Zeroes.js

https://github.com/neetcode-gh/leetcode/blob/main/typescript/172-Factorial-Trailing-Zeroes.ts

类似问题

LeetCode 1006. 笨阶乘

LeetCode 1006. Clumsy Factorial

https://leetcode.com/problems/clumsy-factorial/

https://leetcode.cn/problems/clumsy-factorial/

LeetCode 793. 阶乘函数后 K 个零

LeetCode 793. Preimage Size of Factorial Zeroes Function

https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/
https://leetcode.cn/problems/preimage-size-of-factorial-zeroes-function/

LeetCode 62. 不同路径

LeetCode 62. Unique Paths

https://leetcode.com/problems/unique-paths/

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-10-07 23:18  xgqfrms  阅读(20)  评论(2编辑  收藏  举报