/*****************************************************************************
* Copyright (c) 2006  Daniel Lerch Hostalot <dlerch@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/


/*
   Metodo de factorizacion de Kraitchik
   ====================================

   Partiendo del metodo de factorización de Fermat, Kraitchik propuso 
   utilizar x e y aleatorios de manera que x^2 = y^2 (mod n)

   Encontrar un par x,y que satisfaga esta congruencia no garantiza la 
   factorización del numero n, pero proporciona un 50% de posibilidades 
   de que los divisores de n obtenidos no sean triviales, es decir, ni 1 ni n. 
   De esta manera, se puede obtener un factor de n calculando el maximo 
   comun divisor de n y de x-y.
   mcd(n, x-y)
*/

#include <gmpxx.h>
#include <iostream>

int main(int argc, char *argv[])
{
   using namespace std;

   mpz_class n, x, y, r, p;

   if(argc!=2)
   {
      cerr << "Usage: " << argv[0] << " <n number>" << endl;
      return 0;
   }
   
   n = argv[1];
   mpz_sqrt(x.get_mpz_t(), n.get_mpz_t()); 

   bool found=false;
   while(!found)
   {
      r = x*x % n;
      if(mpz_perfect_square_p(r.get_mpz_t())!=0)
      {
         mpz_sqrt(y.get_mpz_t(), r.get_mpz_t());
         r = (x-y) % n;
         mpz_gcd(p.get_mpz_t(), r.get_mpz_t(), n.get_mpz_t());

         if((1<p)&&(p<n)) found=true;
      }
      x++;
   }

   cout << "factor: " << p << endl;
   return 0;
}







