Tag Archives: #WSQ08

Homework 8: Yo soy 196

We are going to calculate the quantity of Lychrel numbers (natural numbers that doesn’t convert on palindromes after a serie of aditions, for example, 196 is a Lychrel number), natural and made palindromes that are present in a range of integer numbers given by the user.

If we want to convert a non-natural palindrome to a palindrome we have to sum its reverse until we obtain the palindrome.

Using this logic, we can declare some variables that acumulate the reverse and suspect numbers, and evaluate a significant number of times until either do we find the palindrome or do we determine that the given number is Lychrel.

To make all this process I utilized some while loops where I flip the numer and then compare the resulting number with the original one.

You can see my code here…

// El programa usa Big Integer para almacenar más datos. Esta es una librería creada por el maestro.
#include <iostream>
//#include <math.h>
#include <string>
#include "BigIntegerLibrary.hh"
using namespace std;

BigInteger reverse(BigInteger N)
{
  BigInteger M=0, n=N;
  int d=0;

  while(n!=0)
  {
    d++;
    n/=10;
  }

  for (;d>0; d--)
  {
    BigInteger D=1;
    for(int c=0; c<d-1; c++)
      {D*=10;}
    M+=(N%10)*D;
    N/=10;
  }
  return M;
}

int main()
{
  BigInteger n, N, NatPal=0, MadePal=0, Lych=0, m, l;
  string s, S;

cout << "\nLower bound of the sequence: ";
  cin >> s;
  cout << "Upper bound of the sequence: ";
  cin >> S;
  n = stringToBigInteger(s);
  l = n;
  N = stringToBigInteger(S);

  for (; n<=N ; n++)
  {
    BigInteger c=0;
    m=n;
    if (n == reverse(n))
    {NatPal++;}
    else
    {
      do {
        m+=reverse(m);
        c++;
      } while(m!=reverse(m) && c!=30);

      if (c==30)
      {Lych++;}
      else
      {MadePal++;}
    }
  }

  cout << "\nWe are calculating how many natural and made palindromes, as well as Lycherel numbers, there are in the range given...\n\n"<< endl;
  cout << "The results for the range "<< l << " to " << N << " are:\n"<< endl;
  cout << "Natural palindromes: " << NatPal << endl;
  cout << "Made palindromes (Non-Lycherel numbers): " << MadePal << endl;
  cout << "Lycherel candidates: " << Lych << "\n\n";
  return 0;
}