-
Notifications
You must be signed in to change notification settings - Fork 0
Collapse file tree
Files
Search this repository
/
Copy pathindex.tsx
More file actions
More file actions
104 lines (85 loc) · 1.96 KB
/
index.tsx
File metadata and controls
104 lines (85 loc) · 1.96 KB
You must be signed in to make or propose changes
More edit options
Edit and raw actions
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { PRIMES, PRIME_LIMIT } from './primes';
const NUMBER_LIMIT = PRIME_LIMIT * PRIME_LIMIT;
/**
* Handles natural numbers
*/
export function handleNumber(input: string = getRandom()) {
if (!isValid(input)) {
return null;
}
const num = BigInt(input);
const output = {
pageName: `Number ${num}`,
data: {},
};
// Prime factorization
if (num > 1n) {
const { isPrime, primeFactors } = factor(num);
if (isPrime) {
output.pageName = `Prime number ${num}`;
} else {
output.data['Prime factorization'] = (
Object.entries(primeFactors)
.map(([p, exponent]) => exponent === 1n ? `${p}` : `${p}^${exponent}`)
.join(' × ')
);
}
}
// Even or odd
const isEven = num % 2n === 0n;
output.data['Property'] = `${num} is an ${isEven ? 'even' : 'odd'} number.`;
return output;
}
/**
* Validates an input
*/
function isValid(input: string): boolean {
const match = input.match(/^(0|[1-9][0-9]*)$/);
if (!match) {
return false;
}
const num = BigInt(match[1]);
return 0n <= num && num < NUMBER_LIMIT;
}
/**
* Returns a random number
*/
function getRandom(): string {
return `${Math.floor(Math.random() * Number(NUMBER_LIMIT))}`;
}
/**
* Performs prime factorization
*/
function factor(num: bigint) {
// If the number is a known prime
if (PRIMES.has(num)) {
return { isPrime: true };
}
let rest = num;
const primeFactors = {};
// Helper function
const factorOut = (i: bigint) => {
while (rest % i === 0n) {
primeFactors[`${i}`] ??= 0n;
primeFactors[`${i}`]++;
rest /= i;
}
};
// Factor out known primes
for (const p of PRIMES) {
if (p * p > rest) {
break;
}
factorOut(p);
}
// If the number is prime
if (rest === num) {
return { isPrime: true };
}
// Add any remaining prime factor
if (rest > 1n) {
primeFactors[`${rest}`] ??= 0n;
primeFactors[`${rest}`]++;
}
return { primeFactors };
}