#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "iostream"
#include "fstream"
#include "string"
#include "list"
#include "vector"
#include "map"
#include <algorithm>//Sameer, to find the elements
using namespace std;
int factorial(int k)
{
int fact = 1;
for(int counter = k; counter>=1; counter--)
{
fact = fact * counter;
}
return fact;
}
int main()
{ //for permuation of 1,2,3
vector<int> firstperm;//={0,1,2,3,4,5,6,7,
8,9};
//IMP:The first permutation we get here is actually the 0th permutation
in reality. So, in the final answer, we will actually get 1000,001th
permutation. We will need to go back which will be easy because its
lexicographic i.e in order
vector<int> millionthoneloc;
int quo=0;
int millsum=1000000,rem=1;
for(int i=0;i<=9;i++)
{
firstperm.push_back(i);
}
for(int i=9;i>=0;i--)
{
div_t divresult;
divresult = div (millsum,factorial(i));
rem=divresult.rem;
millsum=rem;
quo=divresult.quot;
cout<<endl<<"millsum: "<<millsum;
cout<<" quo: "<<quo;
cout<<" rem: "<<rem;
{
millionthoneloc.push_back(
firstperm[quo]);
firstperm.erase(firstperm.
begin()+quo);
}
}
cout<<endl<<"1,000,001th permutation is: ";
int i1=millionthoneloc.size();
for(int i2=0;i2<i1;i2++)
{
cout<<millionthoneloc[i2];
}
return 0;
}
//Following links were helpful:
//
http://blog.mycila.com/2009/05/project-euler-problem-24.html (Spoiler, this has answer)
//
http://en.wikipedia.org/wiki/Factoradic//
http://www.eggwall.com/2012/01/project-euler-in-r-problem-24.html
//Spoiler alert:
//Answer adjustment explained here. Answer too is mentioned here:
//
So, at 1000,001th -> 2783915604. (since 2nd last digit is 0, this
number is first in the range for 6 i.e after this we will have various 6
combinations i.e after 604 we have 640....)
//So, now lets see what this says about 5 in this permutation. There are
many combinations before this for 5. So, lets adjust what 1,000,000
lexicographic permutation will be.
//4 precedes 6. And the permutation before this one will be the maximum permutation for 4. Hence, it should be 460.
//All in all, the whole number should be 2783915460
//It says that this is the fifth permutation for 5 out of 6 namely:
//5046
//5064
//5406
//5460
//5604
//5640