martes, 10 de abril de 2012

Project Euler 32

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <set>
#include <numeric>
using namespace std;
int factorial(int n)
{
    int f  = 1;
    while(n>0)
        f *= n--;
    return f;
}
int main()
{
    set<int> guardar ;
    string cad =  "123456789";
    int tam =  cad.length();
    int n1,n2,n3,i,j;
    int fac = factorial(tam);

    for(int n = 0 ; n < fac; n++)
    {
        for(i = 1 ; i <=(tam-2) ; i++ )
        {
            n1 = atoi(cad.substr(0,i).data());
            for(j = 1 ; j <= (tam-i-1); j++)
            {
                n2 = atoi(cad.substr(i,j).data());
                n3 = atoi(cad.substr(i+j,tam-i+j).data());
                if((n1*n2) == n3)
                {
                    cout << n1 << " x "<<n2 <<" = "<<n3<<endl;
                    guardar.insert(n3);
                }
            }
        }
        next_permutation(cad.begin(),cad.end());
    }
    cout << "Resultado Final = "<<accumulate(guardar.begin(),guardar.end(),0)<<endl;
    return 0;
}

No hay comentarios:

Publicar un comentario