【ProjectEuler】ProjectEuler_024

来源:互联网 发布:汽车电脑调音软件 编辑:程序博客网 时间:2024/06/10 16:51
// Problem 24// 16 August 2002//// A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are://// 012   021   102   120   201   210//// What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?#include <iostream>#include <windows.h>#include <cassert>using namespace std;// 求某个数的阶乘long Factorial(long num){    if(num <= 1)    {        return 1;    }    else    {        return num * Factorial(num - 1);    }}// 寻找numCount个从0开始的数排列起来第numRemaind个数的首位// 然后从numRemaindArray中找到从小到大的剩余数作为首位// 例如:// numCount=3,numRemaind=4;// 排列为:012,021,102,120,201,210// 第四个数为120,则首位为1// numRemaind表示查找到的数在这单位数中处于第几个,从1开始,最大为unitNumint FindTheFirstNum(int *numRemaindArray, const int numCount , int &numRemaind){    //获取每单位包含多少个数    int unitNum = Factorial(numCount - 1);    //numRemaind必小于总数    assert(numRemaind <= unitNum * numCount);    int index = (numRemaind - 1) / unitNum;    //获取剩余数,如果刚好整除,则在此单位数的最后一个,第unitNum个    numRemaind = numRemaind % unitNum;    if(numRemaind == 0)    {        numRemaind = unitNum;    }    //获取结果的数字    int result = numRemaindArray[index];    //后面的数提前    for(int i = index + 1; i < numCount; i++)    {        numRemaindArray[i - 1] = numRemaindArray[i];    }    //最后置0    numRemaindArray[numCount - 1] = 0;    return result;}void F1(){    cout << "void F1()" << endl;    LARGE_INTEGER timeStart, timeEnd, freq;    QueryPerformanceFrequency(&freq);    QueryPerformanceCounter(&timeStart);    const int NUM_COUNT = 10;//总共的数字    const int INDEX_NUM = 1000000;//要寻找数字的位置    int numRemaindArray[NUM_COUNT];//剩余数的数组    //初始化    for(int i = 0; i < NUM_COUNT; i++)    {        numRemaindArray[i] = i;    }    int numRemaind = INDEX_NUM;    cout << "在0-" << NUM_COUNT - 1 << "这" << NUM_COUNT << "个数字从小到大的排列中,第" << INDEX_NUM << "个为:";    for(int i = NUM_COUNT; i > 0; i--)    {        cout << FindTheFirstNum(numRemaindArray, i, numRemaind);    }    cout << endl;    QueryPerformanceCounter(&timeEnd);    cout << "Total Milliseconds is " << (double)(timeEnd.QuadPart - timeStart.QuadPart) * 1000 / freq.QuadPart << endl;}//主函数int main(){    F1();    return 0;}/*void F1()在0-9这10个数字从小到大的排列中,第1000000个为:2783915460Total Milliseconds is 17.0488By GodMoon*/

原创粉丝点击