Project Euler #125: Palindromic sums

Question
The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 62 + 72 + 82 + 92 + 102 + 112 + 122.
There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums, and the sum of these palindromes is 4164. Note that 1 = 02 + 12 has not been included as this problem is concerned with the squares of positive integers.
Find the sum of all the numbers less than 108 that are both palindromic and can be written as the sum of consecutive squares.

Answer :

Hacker Rank Problem

Solution
 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 java.math.BigInteger;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);
        int numberOfTestCases = in.nextInt();
        for (int i = 0; i < numberOfTestCases; i++) {
            int n = in.nextInt();
            int d = in.nextInt();
            double sqrtLimit = Math.sqrt(n);

            BigInteger sum = BigInteger.valueOf(0);
            HashSet<Long> set = new HashSet<Long>();

            for (int j = 1; j <= sqrtLimit; j++) {
                long number = j * j;
                int k = j + d;
                //System.out.println("j " + j);
                while (number < n && k <= sqrtLimit) {
                    number += k * k;
                    if (number == reverse(number) && number < n) {
                        //System.out.println(k + ":" + number);
                        if (!set.contains(number)) {
                            //System.out.println("addedToSet: " + number);
                            sum = sum.add(BigInteger.valueOf(number));
                            set.add(number);
                        }
                    }
                    k += d;
                }
            }
            System.out.println(sum);
        }
    }

    public static long reverse(long number) {
        long reverse = 0;
        while (number != 0) {
            reverse = reverse * 10 + number % 10;
            number /= 10;
        }
        return reverse;
    }
}

Comments

Popular Posts