Open In App

Sum of first K even-length Palindrome numbers

Improve
Improve
Like Article
Like
Save
Share
Report

Given a integer k, find the sum of first k even-length palindrome numbers. 
Even length here refers to the number of digits of a number is even.

Examples: 

Input : k = 3
Output : 66
Explanation: 11 + 22 + 33  = 66 (Sum 
of first three even-length palindrome 
numbers)


Input : 10
Output : 1496
Explanation: 11+22+33+44+55+66+77+88+
99+1001 = 1496

A naive approach will be to check every even length number, if it is a palindrome number then we sum it up. We repeat the same process for first K even length palindrome numbers and sum them up to get the sum. 

In this case complexity will go high as even length numbers are from 10-99 and then 1000-9999 and then so on… 
10-99, 1000-9999, 100000-999999.. has 9, 90, 900 respectively palindrome numbers in them, so to check k numbers we have to check a lot of numbers which will not be efficient enough.

An efficient approach will be to observe a pattern for even length prime numbers.

11, 22, 33, 44, 55, 66, 77, 88, 99, 1001, 1111, 1221, 1331, 1441, 1551, 1661… 
 

1st number is 11, 2nd is 22, third is 33, 16th is 16-rev(16) i.e., 1661
So the Nth number will int(string(n)+rev(string(n)). 
See here for conversion of integer to string and string to integer.

Below is the implementation of the above approach: 

C++




#include <bits/stdc++.h>
#include <boost/lexical_cast.hpp>
using namespace std;
 
// function to return the sum of
// first K even length palindrome numbers
int sum(int k)
{
    // loop to get sum of first K even
    // palindrome numbers
    int sum = 0;
    for (int i = 1; i <= k; i++) {
 
        // convert integer to string
        string num = to_string(i);
 
        // Find reverse of num.
        string revNum = num;
        reverse(revNum.begin(), revNum.end());
 
        // string(n)+rev(string(n)
        string strnum = (num + revNum);
 
        // convert string to integer
        int number = boost::lexical_cast<int>(strnum);
 
        sum += number; // summation
    }
    return sum;
}
// driver program to check the above function
int main()
{
    int k = 3;
    cout << sum(k);
    return 0;
}


Java




// Java implementation to find sum of
// first K even-length Palindrome numbers
import java.util.*;
import java.lang.*;
 
public class GfG{
 
public static String reverseString(String str)
{
    StringBuilder sb = new StringBuilder(str);   
    sb.reverse();  
    return sb.toString();
}
 
// function to return the sum of
// first K even length palindrome numbers
static int sum(int k)
{
    // loop to get sum of first K even
    // palindrome numbers
    int sum = 0;
    for (int i = 1; i <= k; i++) {
 
    // convert integer to string
    String num = Integer.toString(i);
 
    // Find reverse of num.
    String revNum = num;
    revNum = reverseString(num);
 
    // string(n)+rev(string(n)
    String strnum = (num + revNum);
 
    // convert string to integer
    int number = Integer.parseInt(strnum);
 
    sum += number; // summation
    }
     
    return sum;
}
 
// driver function
public static void main(String argc[])
{
    int n = 3;
    System.out.println(sum(n));
}
}
 
// This code is contributed by Prerna Saini


Python3




# Python3 implementation of the approach
 
# function to return the sum of
# first K even length palindrome numbers
def summ(k):
 
    # loop to get sum of first K even
    # palindrome numbers
    sum = 0
    for i in range(1, k + 1):
 
        # convert integer to string
        num = str(i)
 
        # Find reverse of num.
        revNum = num
        revNum = ''.join(reversed(revNum))
 
        # string(n)+rev(string(n)
        strnum = num + revNum
 
        # convert string to integer
        number = int(strnum)
 
        sum += number # summation
 
    return sum
 
# Driver Code
if __name__ == "__main__":
    k = 3
    print(summ(k))
 
# This code is contributed by
# sanjeev2552


C#




// C# implementation to find sum of
// first K even-length Palindrome numbers
using System;
 
class GfG
{
     
    // function to return the sum of
    // first K even length palindrome numbers
    static int sum(int k)
    {
         
        // loop to get sum of first K even
        // palindrome numbers
        int sum = 0;
        for (int i = 1; i <= k; i++)
        {
 
            // convert integer to string
            String num = Convert.ToString(i);
 
            // Find reverse of num.
            String revNum = num;
            revNum = reverse(num);
 
            // string(n)+rev(string(n)
            String strnum = (num + revNum);
 
            // convert string to integer
            int number = Convert.ToInt32(strnum);
 
            sum += number; // summation
        }
 
        return sum;
    }
     
    static String reverse(String input)
    {
        char[] temparray = input.ToCharArray();
        int left, right = 0;
        right = temparray.Length - 1;
 
        for (left = 0; left < right; left++, right--)
        {
             
            // Swap values of left and right
            char temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right] = temp;
        }
        return String.Join("",temparray);
    }
     
    // Driver code
    public static void Main(String []argc)
    {
        int n = 3;
        Console.WriteLine(sum(n));
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
 
// function to return the sum of
// first K even length palindrome numbers
function sum(k)
{
    // loop to get sum of first K even
    // palindrome numbers
    var sum = 0;
    for (var i = 1; i <= k; i++) {
 
        // convert integer to string
        var num = (i.toString());
 
        // Find reverse of num.
        var revNum = num;
        revNum = revNum.split('').reverse().join('');
 
        // string(n)+rev(string(n)
        var strnum = (num + revNum);
 
        // convert string to integer
        var number = parseInt(strnum);
 
        sum += number; // summation
    }
    return sum;
}
 
 
// driver program to check the above function
var k = 3;
document.write(sum(k));
 
</script>


Output

66

Time Complexity: O(k*log10k), as we are using a loop to traverse k times and we are using the reverse() function in each traversal which will cost O(log10k) as the maximum size of the string we are reversing will be log10k.
Auxiliary Space: O(log10k), as we are using extra space for string of size log10k.

Another Approach:

1. Initialize a variable sum to 0 to keep track of the sum of the palindrome numbers.
2. Initialize a counter variable count to 0 to keep track of the number of palindrome numbers found so far.
3. Initialize a variable i to 1 to start iterating from the first positive integer.
4. Repeat the following steps until count reaches K:
a. Convert the integer i to a string and check if it is a palindrome. If it is, add it to sum and increment count.
b. Increment i to check the next positive integer.
Once count reaches K, sum will contain the sum of the first K even-length palindrome numbers.

C++




#include <bits/stdc++.h>
using namespace std;
 
#define MAX_DIGITS 20
 
bool is_palindrome(char *s) {
    int length = strlen(s);
    for (int i = 0; i < length / 2; i++) {
        if (s[i] != s[length - i - 1]) {
            return false;
        }
    }
    return true;
}
 
int main() {
    int K = 5;
 
    int sum = 0;
    int count = 0;
    int i = 1;
 
    while (count < K) {
        char s[MAX_DIGITS];
        sprintf(s, "%d", i);
 
        if (strlen(s) % 2 == 0 && is_palindrome(s)) {
            sum += i;
            count++;
        }
 
        i++;
    }
    cout<<"Sum of first "<<K<<" even-length palindrome numbers: "<<sum<<endl;
 
    return 0;
}


C




#include <stdio.h>
#include <stdbool.h>
#include <string.h>
 
#define MAX_DIGITS 20
 
bool is_palindrome(char *s) {
    int length = strlen(s);
    for (int i = 0; i < length / 2; i++) {
        if (s[i] != s[length - i - 1]) {
            return false;
        }
    }
    return true;
}
 
int main() {
    int K = 5;
 
    int sum = 0;
    int count = 0;
    int i = 1;
 
    while (count < K) {
        char s[MAX_DIGITS];
        sprintf(s, "%d", i);
 
        if (strlen(s) % 2 == 0 && is_palindrome(s)) {
            sum += i;
            count++;
        }
 
        i++;
    }
 
    printf("Sum of first %d even-length palindrome numbers: %d\n", K, sum);
 
    return 0;
}


Python3




MAX_DIGITS = 20
 
def is_palindrome(s: str) -> bool:
    length = len(s)
    for i in range(length // 2):
        if s[i] != s[length - i - 1]:
            return False
    return True
 
def main():
    K = 5
    sum = 0
    count = 0
    i = 1
 
    while count < K:
        s = str(i)
 
        if len(s) % 2 == 0 and is_palindrome(s):
            sum += i
            count += 1
 
        i += 1
 
    print(f"Sum of first {K} even-length palindrome numbers: {sum}")
 
if __name__ == "__main__":
    main()


C#




using System;
 
class Gfg {
    const int MAX_DIGITS = 20;
 
    static bool is_palindrome(string s) {
        int length = s.Length;
        for (int i = 0; i < length / 2; i++) {
            if (s[i] != s[length - i - 1]) {
                return false;
            }
        }
        return true;
    }
 
    static void Main(string[] args) {
        int K = 5;
 
        int sum = 0;
        int count = 0;
        int i = 1;
 
        while (count < K) {
            string s = i.ToString();
 
            if (s.Length % 2 == 0 && is_palindrome(s)) {
                sum += i;
                count++;
            }
 
            i++;
        }
 
        Console.WriteLine("Sum of first {0} even-length palindrome numbers: {1}", K, sum);
    }
}


Javascript




const MAX_DIGITS = 20;
 
// Function to check if a string is a palindrome
function is_palindrome(s) {
    let length = s.length;
    for (let i = 0; i < Math.floor(length / 2); i++) {
        if (s[i] !== s[length - i - 1]) {
            return false;
        }
    }
    return true;
}
 
// driver code to test above function
let K = 5;
let sum = 0;
let count = 0;
let i = 1;
 
// Loop until we find K even-length palindrome numbers
while (count < K) {
    let s = i.toString();
 
    // Check if the number is an even-length palindrome
    if (s.length % 2 === 0 && is_palindrome(s)) {
        sum += i;
        count += 1;
    }
 
    i += 1;
}
 
console.log(`Sum of first ${K} even-length palindrome numbers: ${sum}`);


Java




import java.util.*;
 
public class Main {
    public static boolean isPalindrome(String s) {
        int length = s.length();
        for (int i = 0; i < length / 2; i++) {
            if (s.charAt(i) != s.charAt(length - i - 1)) {
                return false;
            }
        }
        return true;
    }
 
    public static void main(String[] args) {
        int K = 5;
        int sum = 0;
        int count = 0;
        int i = 1;
 
        while (count < K) {
            String s = Integer.toString(i);
 
            if (s.length() % 2 == 0 && isPalindrome(s)) {
                sum += i;
                count++;
            }
 
            i++;
        }
 
        System.out.println("Sum of first " + K + " even-length palindrome numbers: " + sum);
    }
}
// This code is contributed by Prajwal kandekar


Output

Sum of first 5 even-length palindrome numbers: 165

Time Complexity: O(K*N) where K is the number of even-length palindrome numbers to find and N is the maximum number of digits in any of the palindrome numbers.
Auxiliary Space: O(N) since we only need to store the string representation of each number.



Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads