-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
94 lines (74 loc) · 2.19 KB
/
main.ts
File metadata and controls
94 lines (74 loc) · 2.19 KB
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
function isPandigital(x: number, n: number): boolean {
if (n < 1 || n > 9){
throw new Error("Invalid value for n, It should be a number between 1 and 9.")
}
const xStr: string = x.toString()
if (xStr.length != n){
return false
}
for (let i=1;i<=n;i++){
if (!xStr.includes(i.toString())) return false
}
return true;
}
function isPrime(x: number): boolean {
for (let i = 2; i<=Math.sqrt(x);i++){
if (x%i==0) {
return false
}
}
return true
}
function arrayFromOneToN(n: number): number[] {
const result: number[] = [];
for (let i = 1; i <= n; i++) {
result.push(i);
}
return result;
}
function arrayToNumber(arr: number[], base: number): number{
let value: number = 0
for (let i=arr.length-1; i>=0; i--){
const position: number = (arr.length-1) - i
value += arr[i] * (base**position)
}
return value
}
function permute(digits: number[]): number[]{
const permutations: number[][] = []
function _permute(current: number[], remaining: number[]): void{
if (remaining.length==0){
permutations.push([...current])
return
}
for (let i=0; i< remaining.length; i++){
current.push(remaining[i])
const nextRemaining: number[] = [...remaining.slice(0, i), ...remaining.slice(i+1)]
_permute(current, nextRemaining)
current.pop()
}
return
}
_permute([], digits)
const results: number[] = []
for (let i=0; i< permutations.length; i++){
results.push(arrayToNumber(permutations[i], 10))
}
return results
}
let max: number = 1;
const startTime: number = performance.now()
for (let i=1; i<=9; i++){
const digits: number[] = arrayFromOneToN(i)
const numbers = permute(digits)
for (let num of numbers){
if (isPrime(num) && isPandigital(num, i)){
if (num > max){
max = num
}
}
}
}
const stopTime: number = performance.now()
const elapsed: number = stopTime - startTime
console.log(`biggest n digit prime & pandigital number = ${max} (elapsed = ${elapsed}ms)`)