The Program in C++ Program to Check if a number is Lychrel number or not is given below:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isPalindrome(int num) {
string str = to_string(num);
string reverseStr = str;
reverse(reverseStr.begin(), reverseStr.end());
return str == reverseStr;
}
bool isLychrel(int num) {
int iteration = 0;
while (iteration < 50) {
int reverseNum = 0;
int tempNum = num;
// Reverse the number
while (tempNum > 0) {
reverseNum = reverseNum * 10 + tempNum % 10;
tempNum /= 10;
}
// Add the number to its reverse
num += reverseNum;
// Check if the result is a palindrome
if (isPalindrome(num)) return false;
iteration++;
}
return true;
}
int main() {
int num;
cout << "Hello Codeauri Family,enter a number here to check if it is Lychrel number or not!:\n ";
cin >> num;
if (isLychrel(num))
cout << num << " is a Lychrel number" << endl;
else
cout << num << " is not a Lychrel number" << endl;
return 0;
}
Output:
Hello Codeauri Family,enter a number here to check if it is Lychrel number or not!:
196
196 is a Lychrel number
Pro-Tips💡
This program uses two functions: isPalindrome
and isLychrel
.
The function isPalindrome
takes an integer as input and returns a boolean indicating whether the number is a palindrome or not.
The function isLychrel
takes an integer as input and returns a boolean indicating whether the number is a Lychrel number or not.
The function isLychrel
first reverses the number, adds it to the original number, and then checks if the result is a palindrome.
If it is not a palindrome, the process is repeated for up to 50 iterations.
If the result is still not a palindrome after 50 iterations, the number is considered to be a Lychrel number
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.