-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0866-prime-palindrome.js
More file actions
60 lines (52 loc) · 1.4 KB
/
0866-prime-palindrome.js
File metadata and controls
60 lines (52 loc) · 1.4 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
/**
* Prime Palindrome
* Time Complexity: O(P)
* Space Complexity: O(log P)
*/
var primePalindrome = function (initialN) {
let currentNum = initialN;
while (true) {
let numAsString = currentNum.toString();
let numLength = numAsString.length;
if (numLength % 2 === 0 && currentNum > 11) {
let nextOddLengthStart = Math.pow(10, numLength);
currentNum = nextOddLengthStart;
continue;
}
let isCurrentValuePalindrome = checkStringPalindrome(numAsString);
if (!isCurrentValuePalindrome) {
currentNum++;
continue;
}
let isCurrentValuePrime = checkIfPrime(currentNum);
if (isCurrentValuePrime) {
return currentNum;
}
currentNum++;
}
};
function checkIfPrime(numValue) {
if (numValue <= 1) return false;
if (numValue <= 3) return true;
if (numValue % 2 === 0 || numValue % 3 === 0) return false;
let testDivisor = 5;
while (testDivisor * testDivisor <= numValue) {
if (numValue % testDivisor === 0 || numValue % (testDivisor + 2) === 0) {
return false;
}
testDivisor += 6;
}
return true;
}
function checkStringPalindrome(targetString) {
for (
let startCharIndex = 0, endCharIndex = targetString.length - 1;
startCharIndex < endCharIndex;
startCharIndex++, endCharIndex--
) {
if (targetString[startCharIndex] !== targetString[endCharIndex]) {
return false;
}
}
return true;
}