#include <iostream>
#include <cstdlib>

using namespace std;

int 
leftover(int text, int key)
{
   int temp = text % key;
   temp = text - temp;
   return temp;
}

int
next_factor(int text, 
            int key, 
            int & left, 
            int & mid, 
            int & right) 
{ 
   int temp;
   bool found = false;
   while((text % key) != 0 && key < text) {
      temp = leftover(text, key);
      if(found) {
         key++;
      }
      else if(temp < mid) {
         right = mid;
         mid = mid / 2;
         key = mid;
         found = true;
      }
      else if(temp > mid) {
         left = mid;
         mid += mid / 2;
         key = mid;
         found = true;
      }
      else {
         key++;
      }
   }
   return key;
}

int
main()
{
   int key = 1234;
   
   int key2;

   int plain_text = 112233;
   
   int cypher_text = plain_text * key;
   
   int left = 1;
   
   int mid = 1000000 / 2;

   int right = 1000000;

   key2 = mid;

   cout << "cypher_text == " << cypher_text << endl;
   
   while(plain_text != (cypher_text / key2) && key2 < cypher_text) {
      key2++;

      cout << "key2 == " << key2 << endl;

      key2 = next_factor(cypher_text, key2, left, mid, right);
   }
   
   plain_text = cypher_text / key2;

   cout << "plain_text == " << plain_text << endl;

   cout << "key2 == " << key2 << endl;
   
   return 0;
}

