Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function () {
- class Result {
- constructor(palindrome, left, right) {
- this.palindrome = palindrome;
- this.left = left;
- this.right = right;
- }
- }
- class Checker {
- constructor() {
- this.digits = new Array(10).fill(0);
- }
- isPalindrome(value) {
- const digits = this.digits;
- let i = 0;
- while (value > 0) {
- digits[i] = value % 10;
- i++;
- value = ~~(value / 10);
- }
- const limit = i >> 1;
- for (let j = 0; j < limit; j++) {
- if (digits[j] !== digits[i - 1 - j]) {
- return false;
- }
- }
- return true;
- }
- }
- function getPrimeNumbers(from, to) {
- // start from zero, so + 1
- const size = to + 1;
- const variants = new Array(size).fill(true);
- const limit = Math.ceil(Math.sqrt(to));
- // Sieve of Eratosthenes
- for (let i = 2; i < limit; i++) {
- if (variants[i]) {
- for (let j = i * i; j < size; j += i) {
- variants[j] = false;
- }
- }
- }
- const result = [];
- for (let i = from; i < size; i++) {
- if (variants[i]) {
- result.push(i);
- }
- }
- return result;
- }
- function findResult() {
- // Max possible result, all 10-digits palindromes % 11 == 0
- const max = 999999999;
- const numbers = getPrimeNumbers(10000, 99999);
- const size = numbers.length;
- const checker = new Checker();
- let result = new Result(0, 0, 0);
- for (let i = 0; i < size; i++) {
- for (let j = i + 1; j < size; j++) {
- const left = numbers[i];
- const right = numbers[j];
- const possible = left * right;
- if (possible > max) {
- break;
- }
- if (possible > result.palindrome && checker.isPalindrome(possible)) {
- result = new Result(possible, left, right);
- }
- }
- }
- return result;
- }
- const startTime = Date.now();
- const result = findResult();
- const endTime = Date.now();
- document.getElementById("js-palindrome").innerHTML = result.palindrome.toString();
- document.getElementById("js-prime-number-left").innerHTML = result.left.toString();
- document.getElementById("js-prime-number-right").innerHTML = result.right.toString();
- document.getElementById("js-duration").innerHTML = (endTime - startTime).toString();
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement