Project Euler #125: Palindromic sums

Sort by

recency

|

26 Discussions

|

  • + 0 comments

    100/- Points C++

    #include <vector>
    #include <iostream>
    #include <algorithm>
    
    // return true if x is a palindrome
    bool isPalindrome(unsigned int x)
    {
      auto reduced = x / 10;
      auto reverse = x % 10;
      // fast exit: a trailing zero can't create a palindrome
      if (reverse == 0)
        return false;
    
      while (reduced > 0)
      {
        // chop off the lowest digit and append it to "reverse"
        reverse *= 10;
        reverse += reduced % 10;
        reduced /= 10;
      }
    
      // palindrome ? both must be equal
      return reverse == x;
    }
    
    
    int main()
    {
      unsigned int tests = 1;
      std::cin >> tests;
      while (tests--)
      {
        unsigned int limit  = 100000000;
        unsigned int stride = 1; // distance between consecutive square numbers
    
        std::cin >> limit >> stride;
    
        std::vector<unsigned int> solutions;
        for (unsigned long long first = 1; 2*first*first < limit; first++)
        {
          auto next = first + stride;
          // sum of a^2 + b^2 + ...
          auto current = first * first + next * next;
          // still within the limit ?
          while (current < limit)
          {
            // check
            if (isPalindrome(current))
              solutions.push_back(current);
    
            // add one element to the sequence
            next    += stride;
            current += next * next;
          }
        }
    
        // sort ...
        std::sort(solutions.begin(), solutions.end());
        // .. and remove duplicates
        auto garbage = std::unique(solutions.begin(), solutions.end());
        solutions.erase(garbage, solutions.end());
    
        // count all solutions
        unsigned long long sum = 0;
        for (auto x : solutions)
          sum += x;
    
        std::cout << sum << std::endl;
      }
    
      return 0;
    }
    
  • + 1 comment

    Works fine for sample test case 0 and sample test case 34. All other cases failed. Can someone help me please? Thanks.!`

    for (int i = 0; i < T; i++) {

    for (unsigned long long j = 1;; j++)
    {
      if (j * j >= case1[i].Num)
        break;
      sum = 0;
      count = 0;
      for (int k = j;; k = k + case1[i].dif)
      {
        sum = sum + k * k;
        count++;
        if (sum >= case1[i].Num)
          break;
        sprintf(str1, "%llu", sum);
        for (p = 0, q = strlen(str1); str1[p] != '\0'; p++, q--)
        {
          str2[q - 1] = str1[p];
        }
        str2[p] = '\0';
    
        if (strcmp(str1, str2) == 0 && count >= 2)
        {
          for (unsigned long long l = 0; l < r; l++)
          {
            if (sum == sums[i])
            {
              flag = 0;
            }
          }
          if (flag)
          {
            Lsum = Lsum + sum;
            sums[r] = sum;
            r++;
          }
        }
      }
    }
    printf("%llu\n", Lsum);
    Lsum = 0;
        }
    

    }

    return 0; }

  • + 0 comments

    find my java solution here

  • + 0 comments

    This times out whenever difference is 1. (Ignore the main)

    from math import *
    
    # Returns a congruence class of a specified modulus and residue,
    # constrained in [lower, upper]
    def congruence_class(residue, modulus, lower, upper, order = 'asc'):
        residue = residue % modulus
        strict_lower = (lower//modulus)*modulus + residue
        if strict_lower < lower: strict_lower += modulus
        strict_upper = (upper//modulus)*modulus + residue
        if strict_upper > upper: strict_upper -= modulus
        if order == 'asc':
            return range(strict_lower, strict_upper + 1, modulus)
        elif order == 'desc':
            return range(strict_upper, strict_lower - 1, -modulus)
    
    # Returns true if any consecutive sequence of numbers
    # in the desc sorted array adds up to target
    def is_consecutive_sum(desc_array, start, end, target):
        #print("desc_array [{0}:{1}] = {2}".format(start, end, desc_array[start:end]))
        if (end - start) <= 1:
            return False
        result = sum(desc_array[start:end])
        if result == target:
            return True
        elif result > target:
            return\
            is_consecutive_sum(desc_array, start, end-1, target)\
            or\
            is_consecutive_sum(desc_array, start+1, end, target)
        else:
            return False
    
    # Checks every congruence class            
    def is_palindrome_sum_of_squares(number, difference):
        limit = int(sqrt(number)) #The limit can be optimized?
        for i in range(0, difference):
            AP = congruence_class(i, difference, 1, limit, 'desc')
            squaredAP = list(map(lambda x: x*x, AP))
            if is_consecutive_sum(squaredAP, 0, len(squaredAP), number):
                return True
    
    # Generator to yield palindromes 
    def generate_palindromes(start, stop, step = 1):
        for x in range(start, stop, step):
            if str(x) == str(x)[::-1]:
                yield x
    
    # What the problem actually requires
    def sum_of_desired_palindromes(number, difference):
        palindrome_sums = 0
        for i in generate_palindromes(1, number+1):
            if is_palindrome_sum_of_squares(i, difference):
                palindrome_sums += i
        return palindrome_sums
            
    if __name__ == "__main__":
        print(sum_of_desired_palindromes(10, 1))
        
    
  • + 0 comments

    brute froce approach is not working it is showing TLE how can i optimize more , any suggestions ???