Skip navigation

This one took about 10 seconds to execute:

#include <iostream>
#include <math.h>
#include <stack>

int main (int argc, char * const argv[]) {

    int answer = 0;
    int size = 0;
    int left_side = 0;
    int right_side = 0;
    int place_holder;
    int product;
    int numDigits;
    int left;
    int right;
    int top;  
    int power;
    int stackingRight;
    int stackingPower;
    int tmp;
    int leftLen;
    int leftToLose;
    int rightGone;
    int reversedLeft;
    int i;
    std::stack<int> pieces;
    bool go = true;

    std::cout << "Provide a digit size to find the largest palindrome made from its products: ";
    std::cin >> size;
    left_side = pow(10,size) - 1;
    right_side = left_side;
    place_holder = right_side;
    
    answer = 0;
    while(left_side > 0 && go){
      right_side = place_holder;
      while(right_side > 0 && go){
        product = left_side * right_side;
        numDigits = floor(log10(product)) + 1;
        //even number of digits required for palindrome
        if(!(numDigits % 2)){
          tmp = floor(numDigits/2);
          power = floor(pow(10, tmp));
          left = floor(product/power);
          top = left * power;
          right = product - top;

          leftLen = (log10(left)) + 1;
          for(i = 0;i < leftLen; i++){
            stackingPower = pow(10, i);
            rightGone = left/stackingPower;
            leftToLose = floor(rightGone/10) * 10;
            stackingRight = rightGone - leftToLose;
            pieces.push(stackingRight);
          } 
          tmp = 0;
          reversedLeft = 0;
          while(!(pieces.empty())){
            reversedLeft += pieces.top() * pow(10, tmp++);
            pieces.pop();
          }
          if(right == reversedLeft){
            if(product > answer){
              answer = product;
            }
          }
        }
        right_side--;
      }
      left_side--;
    }

    std::printf("Size: %d left_side: %d right_side: %d numDigits: %d Answer: %d \n", size, left_side, right_side, numDigits, answer);
    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: