Trusted answers to developer questions

Ayesha Naeem

**Lychrel numbers** are natural numbers that can never form a palindrome after an iterative process of adding the number to its reverse. The first few numbers that fail to form a palindrome are known as lychrel numbers.

- To determine if a number is lychrel, check if the number is a palindrome or not.
- If the number is a palindrome, the number is not a lychrel; otherwise, the number is added to its reverse and the new number is checked as a palindrome.
- The process is repeated until a palindrome is found.
- For example, the number 35 is not a palindrome. In the first iteration, 35 is added to 53 to form 88. The number 88 is a palindrome, therefore it takes one iteration to prove that 35 is not a lychrel.

The following code demonstrates how to find lychrel numbers in C++:

#include <iostream> using namespace std; int reverse(int num) { int reversed = 0; while(num>0) { int mod = num%10; reversed = (reversed*10) + mod; num = num/10; } return reversed; } void isLychrel(int num, int max) { //variable that holds 0 if lychrel and 1 if not int lychrel = 0; //duplicate the number for checking later int num_temp=num; while(num>0) { // get the reverse int palindrome = reverse(num); // compare with original if(palindrome == num) { // set the check to 1 and exit loop lychrel = 1; break; } // if not a palindrom, reverse the number and add to the original number num = reverse(num) + num; // decrease the iteration count max--; } // display results if(lychrel) { cout<< "The number "<<num_temp<<" is not lycheral."<<endl; } else { cout<< "The number "<<num_temp<<" is lycheral."<<endl; } } int main() { int max = 10; int num_1 = 35; int num_2 = 295; //check if the number is lychrel or not isLychrel(num_1, max); isLychrel(num_2, max); }

For the sake of implementation, the above code uses a maximum number to limit the iterations. If a palindrome is found within the limit, it is not lychrel.

- The program is implemented for two numbers, 35 and 295.
- The program calls the
`isLychrel`

function, which performs iterations until it finds a palindrome or reaches the maximum limit of iterations. - The
`isLychrel`

function calls the`reverse`

function and compares the returned value with the original value to check if the original number is a palindrome or not. - If the number is not a palindrome, the program calls the
`reverse`

function again, adds the returned value to the original number, and repeats the process.

RELATED TAGS

CONTRIBUTOR

Ayesha Naeem

Copyright ©2022 Educative, Inc. All rights reserved

RELATED COURSES

View all Courses

Keep Exploring

Related Courses