Trusted answers to developer questions

How to find the sum of first n palindromes

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Given an integer n , return the sum of the first n palindromes.

Constraints

1 <= n <= 10000 , where n is the integer.

Palindrome

A palindrome is a word, number, phrase, or sequence of characters that reads the same backward as it does forward (e.g., madam, racecar, 909, etc.)

Example

Input :
5
Output :
15

Explanation
The sum of the first 5 palindromes (1, 2, 3, 4, 5) is 15.

Implementation

First, we input the value of n using the input() function. Then, we initialize the variables sum and count to 0.

sum=0
count=0

Next, we enter the for loop where we can iterate the loop for any number of times. However, in this case, we will use it till 10,000, but you can change the end value to any number you wish.

for i in range(1,10000) :

Once inside the loop, the first step is to convert the number to a string, i.e., reverse the string using [::-1]. Next, we compare the reversed number to the actual number and, if they are the same, we can calculate the sum by:

sum=sum+1

Then, we count the number of times the actual number is reversed using:

count=count+1

Once the count has reached the n value, we use break to terminate the loop.
We then print the sum of n palindromes in the next line.
The code is given below:

n=int(5)
count=0
sum=0
for i in range(1,10000) :
x=str(i) #changes i to str
y=x[::-1] #reverses the number
if x==y :
sum =sum+i
count=count+1
if count==n :
break
print("sum=" ,sum) #prints the sum

Space complexity

The program uses integer n, which takes O(1). But, the complexity of the result, that is the size of “sum from 1 to n," is n(n – 1) / 2 is O(n ^ 2).

RELATED TAGS

python
Did you find this helpful?