-
Notifications
You must be signed in to change notification settings - Fork 0
/
perfect.ts
48 lines (38 loc) · 1.22 KB
/
perfect.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import prompts from "prompts";
/**
* Fetch an array of all the factors of a `num`, **excluding
* `num` itself.**
*/
function getFactors(num: number): number[] {
// Get every number from 1 to `num / 2` in an array
let possibleFactors = Array.from(Array(Math.ceil(num / 2)), (_, i) => i + 1);
// FIlter to only include actual factors
possibleFactors = possibleFactors.filter((fact) => num % fact === 0);
possibleFactors.forEach((x) => {
const otherFact = num / x;
if (!possibleFactors.includes(otherFact)) possibleFactors.push(otherFact);
});
return possibleFactors;
}
/**
* Reducer function to sum an array.
*/
const sumReducer = (acc: number, thisNum: number) => acc + thisNum;
(async () => {
const out = await prompts({
type: "number",
name: "num",
message: "Check if perfect",
validate: (value: number) => (value < 1 ? `Number must be >= 1` : true),
});
const factors = getFactors(out.num);
const sumOfFactors = factors.reduce(sumReducer, 0);
// console.log(factors);
// console.log(sumOfFactors);
// console.log(out.num);
if (sumOfFactors === out.num) {
console.log(`${out.num} is a perfect number`);
} else {
console.log(`${out.num} is NOT a perfect number`);
}
})();