add: 完美数

This commit is contained in:
yi-ge 2020-05-22 13:30:10 +08:00
parent bf6f71f55f
commit 6a8d487f93
3 changed files with 27 additions and 0 deletions

View File

@ -367,6 +367,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 560. 和为K的子数组 <https://leetcode-cn.com/problems/subarray-sum-equals-k/>
- LintCode 838. 子数组和为K <https://www.lintcode.com/problem/subarray-sum-equals-k/description>
- [完美数](src/math/perfect-number.js)
- LeetCode 507. 完美数 <https://leetcode-cn.com/problems/perfect-number/>
- LintCode 1199. 完美的数 <https://www.lintcode.com/problem/perfect-number/description>
## 堆
- [超级丑数](src/stack/super-ugly-number.js)【未完成】

View File

@ -0,0 +1,16 @@
const pn = (p) => { // 欧几里得-欧拉定理
return (1 << (p - 1)) * ((1 << p) - 1)
}
/**
* @param {number} num
* @return {boolean}
*/
export const checkPerfectNumber = function (num) {
const primes = [2, 3, 5, 7, 13, 17, 19, 31]
for (const prime of primes) {
if (pn(prime) === num) return true
}
return false
}

View File

@ -0,0 +1,6 @@
import { checkPerfectNumber } from '../../src/math/perfect-number'
test('完美数', () => {
expect(checkPerfectNumber(28)).toBe(true)
expect(checkPerfectNumber(2)).toBe(false)
})