【ProjectEuler】ProjectEuler_051(找出最小的能够通过改变同一部分得到八个质数的质数)

#pragma once

#include 
#include 
#include 

using namespace std;

class MoonMath
{
public:
    MoonMath(void);
    ~MoonMath(void);

    //************************************
    // Method:    IsInt
    // Access:    public
    // Describe:  判断double值在epsilon的范围内是否很接近整数
    //            如1.00005在epsilon为0.00005以上就很接近整数
    // Parameter: double doubleValue    要判断的double值
    // Parameter: double epsilon        判断的精度,0 < epsilon < 0.5
    // Parameter: INT32 & intValue      如果接近,返回最接近的整数值
    // Returns:   bool                  接近返回true,否则返回false
    //************************************
    static bool IsInt(double doubleValue, double epsilon, INT32 &intValue);

    //************************************
    // Method:    Sign
    // Access:    public
    // Describe:  获取value的符号
    // Parameter: T value   要获取符号的值
    // Returns:   INT32     正数、0和负数分别返回1、0和-1
    //************************************
    template 
    static INT32 Sign(T value);

    const static UINT32 MIN_PRIMER = 2;     // 最小的素数

    //************************************
    // Method:    IsPrimer
    // Access:    public
    // Describe:  判断一个数是否是素数
    // Parameter: UINT32 num    要判断的数
    // Returns:   bool          是素数返回true,否则返回false
    //************************************
    static bool IsPrimer(UINT32 num);

    //************************************
    // Method:    IsIntegerSquare
    // Access:    public static
    // Describe:  判断给定的数开平方后是否为整数
    // Parameter: UINT32 num
    // Returns:   bool
    //************************************
    static bool IsIntegerSquare(UINT32 num);

    //************************************
    // Method:    GetDiffPrimerFactorNum
    // Access:    public static
    // Describe:  获取num所有的不同质因数
    // Parameter: UINT32 num
    // Returns:   set
    //************************************
    static set MoonMath::GetDiffPrimerFactorNum(UINT32 num);
};


#include "MoonMath.h"
#include 

MoonMath::MoonMath(void)
{
}


MoonMath::~MoonMath(void)
{
}

template 
INT32 MoonMath::Sign(T value)
{
    if(value > 0)
    {
        return 1;
    }
    else if(value == 0)
    {
        return 0;
    }
    else
    {
        return -1;
    }
}

bool MoonMath::IsInt(double doubleValue, double epsilon, INT32 &intValue)
{
    if(epsilon > 0.5 || epsilon < 0)
    {
        return false;
    }

    if(INT32(doubleValue + epsilon) == INT32(doubleValue - epsilon))
    {
        return false;
    }

    INT32 value = INT32(doubleValue);

    intValue = (fabs(doubleValue - value) > 0.5) ? (value + MoonMath::Sign(doubleValue)) : (value) ;
    return true;
}

bool MoonMath::IsPrimer(UINT32 num)
{
    if(num < MIN_PRIMER)
    {
        return false;
    }

    if(num == MIN_PRIMER)
    {
        return true;
    }

    // 判断是否能被2整除
    if((num & 1) == 0)
    {
        return false;
    }

    UINT32 sqrtOfNum = (UINT32)sqrt((double)num); // num的2次方

    // 从MIN_PRIMER到sqrt(num),如果任何数都不能被num整除,num是素数,否则不是
    for(UINT32 i = MIN_PRIMER + 1; i <= sqrtOfNum; i += 2)
    {
        if(num % i == 0)
        {
            return false;
        }
    }

    return true;
}

bool MoonMath::IsIntegerSquare(UINT32 num)
{
    UINT32 qurtNum = (UINT32)sqrt((double)num);

    return (qurtNum * qurtNum) == num;
}

set MoonMath::GetDiffPrimerFactorNum(UINT32 num)
{
    UINT32 halfNum = num / 2;
    set factors;

    for(UINT32 i = 2; i <= halfNum; ++i)
    {
        if(!MoonMath::IsPrimer(i))
        {
            continue;
        }

        if(num % i == 0)
        {
            factors.insert(i);

            while(num % i == 0)
            {
                num /= i;
            }
        }
    }

    return factors;
}


// Prime digit replacements
//     Problem 51
//     By replacing the 1st digit of *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
//
//     By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
//
//     Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.
//
// 题目51:找出最小的能够通过改变同一部分得到八个质数的质数。
// 通过置换*3的第一位得到的9个数中,有六个是质数:13,23,43,53,73和83。
//
//     通过用同样的数字置换56**3的第三位和第四位,这个五位数是第一个能够得到七个质数的数字,得到的质数是:56003, 56113, 56333, 56443, 56663, 56773, 和 56993。因此其中最小的56003就是具有这个性质的最小的质数。
//
//     找出最小的质数,通过用同样的数字置换其中的一部分(不一定是相邻的部分),能够得到八个质数。

#include 
#include 
#include 
#include 

#include 
#include 

using namespace std;

// 打印时间等相关信息
class DetailPrinter
{
public:
    void Start();
    void End();
    DetailPrinter();

private:
    LARGE_INTEGER timeStart;
    LARGE_INTEGER timeEnd;
    LARGE_INTEGER freq;
};

DetailPrinter::DetailPrinter()
{
    QueryPerformanceFrequency(&freq);
}

//************************************
// Method:    Start
// Access:    public
// Describe:  执行每个方法前调用
// Returns:   void
//************************************
void DetailPrinter::Start()
{
    QueryPerformanceCounter(&timeStart);
}

//************************************
// Method:    End
// Access:    public
// Describe:  执行每个方法后调用
// Returns:   void
//************************************
void DetailPrinter::End()
{
    QueryPerformanceCounter(&timeEnd);
    cout << "Total Milliseconds is " << (double)(timeEnd.QuadPart - timeStart.QuadPart) * 1000 / freq.QuadPart << endl;

    const char BEEP_CHAR = '\007';

    cout << endl << "By GodMoon" << endl << __TIMESTAMP__ << BEEP_CHAR << endl;

    system("pause");
}

/*************************解题开始*********************************/

const UINT32 RADIO = 10;                    // 进制

// 记录最小素数,可以增加的数以及可增加的次数
// 比如56003,可以增加的数为100,110,10,可增加的次数分别为9,9,9
struct FitInfo
{
    UINT32 Num;
    vector IncNums;
    vector MaxIncTimes;

    void Clear();
    void AddIncNum(UINT32 incNum, UINT32 maxIncTimes);
};

//************************************
// Method:    Clear
// Access:    public
// Describe:  清空信息
// Returns:   void
//************************************
void FitInfo::Clear()
{
    Num = 0;
    IncNums.clear();
    MaxIncTimes.clear();
}

//************************************
// Method:    AddIncNum
// Access:    public
// Describe:
// Parameter: UINT32 incNum
// Parameter: UINT32 maxIncTimes
// Returns:   void
//************************************
void FitInfo::AddIncNum(UINT32 incNum, UINT32 maxIncTimes)
{
    IncNums.push_back(incNum);
    MaxIncTimes.push_back(maxIncTimes);
}

//************************************
// Method:    GetFitInfo
// Access:    public
// Describe:  获取这个数的信息,替换连续的相同数字
// Parameter: UINT32 num
// Parameter: FitInfo & fitInfo
// Returns:   void
//************************************
void GetAdjacentFitInfo(UINT32 num, FitInfo &fitInfo, UINT32 familyPrimerCount)
{
    UINT32 numBak = num;            // 备份num,用于循环
    UINT32 currDigit;               // 当前处理的数字
    UINT32 lastDigit = num % RADIO; // 前一个处理的数字,初始化为第一个数字
    UINT32 currWeight = 1;          // 当前位的权重,为1,10,100……
    UINT32 currIncNum = 0;          // 当前num可增加的数
    UINT32 addNum;                  // 用于递增计算连续可用的递增数
    UINT32 incNum;                  // 用于保存连续可用的递增数

    fitInfo.Clear();
    fitInfo.Num = num;

    while(numBak != 0)
    {
        currDigit = numBak % RADIO;
        if(currDigit <= RADIO - familyPrimerCount)
        {
            // 如果上一个数字和当前数字一致,将其组合加入fitInfo
            if(lastDigit == currDigit)
            {
                currIncNum += currWeight;

                addNum = currWeight;
                for(incNum = currWeight; incNum < currIncNum; incNum += addNum)
                {
                    addNum /= RADIO;
                    fitInfo.AddIncNum(incNum, RADIO - currDigit - 1);
                }
            }
            else
            {
                // 不一致的话,只添加currWeight
                currIncNum = currWeight;
            }

            fitInfo.AddIncNum(currIncNum, RADIO - currDigit - 1);
        }
        else
        {
            currIncNum = 0;
        }

        currWeight *= 10;
        lastDigit = currDigit;
        numBak /= RADIO;
    }
}

//************************************
// Method:    GetNumMap
// Access:    public
// Describe:  获取
// Parameter: UINT32 num
// Parameter: UINT32 digitIncNum[]  二进制的数字map,表示索引的数字所在十进制数中的位置
// Parameter: UINT32 radio
// Returns:   void
//************************************
void GetNumMap(UINT32 num, UINT32 digitIncMap[], UINT32 radio)
{
    UINT32 currDigit;
    UINT32 currWeight = 1;

    while(num != 0)
    {
        currDigit = num % radio;
        digitIncMap[currDigit] |= currWeight;
        currWeight <<= 1;
        num /= radio;
    }
}

//************************************
// Method:    GetIncWeight
// Access:    public 
// Describe:  根据二进制Map获取可加权重
// Parameter: UINT32 digitIncMap            如:1010B
// Parameter: vector & incWeight    如:1000,10
// Returns:   void
//************************************
void GetIncWeight(UINT32 digitIncMap, vector &incWeight)
{
    UINT32 currWeight = 1;
    incWeight.clear();

    while(digitIncMap != 0)
    {
        if((digitIncMap & 1))
        {
            incWeight.push_back(currWeight);
        }
        currWeight *= RADIO;
        digitIncMap >>= 1;
    }
}

//************************************
// Method:    GetValue
// Access:    public
// Describe:  从map和权重中获取值
// Parameter: UINT32 map                    数据位,如:101
// Parameter: vector & incWeight    权重,如:1000,100,1
// Returns:   UINT32                        值:如:1001
//************************************
UINT32 GetValue(UINT32 map, const vector &incWeight)
{
    UINT32 value;
    UINT32 index;

    for(value = 0, index = 0; map; ++index)
    {
        if(map & 1)
        {
            value += incWeight[index];
        }

        map >>= 1;
    }

    return value;
}

//************************************
// Method:    ParseDigitMap
// Access:    public
// Describe:  从digitIncMap中计算出相应数字的fitInfo
// Parameter: UINT32 digitIncMap    表示数字digit的所在位比如10101101
// Parameter: UINT32 digit          范围[0,RADIO),表示某个数字
// Parameter: FitInfo & fitInfo
// Returns:   void
//************************************
void ParseDigitMap(UINT32 digitIncMap, UINT32 digit, FitInfo &fitInfo)
{
    vector incWeight;

    GetIncWeight(digitIncMap, incWeight);

    UINT32 maxMapValue = 1 << incWeight.size();

    for(UINT32 mapValue = 1; mapValue < maxMapValue; ++mapValue)
    {
        fitInfo.AddIncNum(GetValue(mapValue, incWeight), RADIO - digit - 1);
    }
}

//************************************
// Method:    GetFitInfo
// Access:    public
// Describe:  获取这个数的信息,替换不一定连续的相同数字
// Parameter: UINT32 num
// Parameter: FitInfo & fitInfo
// Returns:   void
//************************************
void GetNotAdjacentFitInfo(UINT32 num, FitInfo &fitInfo, UINT32 familyPrimerCount)
{
    UINT32 digitIncMap[RADIO] = {0};

    fitInfo.Clear();
    fitInfo.Num = num;

    GetNumMap(num, digitIncMap, RADIO);

    for(UINT32 digit = 0; digit < RADIO; ++digit)
    {
        ParseDigitMap(digitIncMap[digit], digit, fitInfo);
    }
}

//************************************
// Method:    CalcMaxPrimerCount
// Access:    public
// Describe:  获取此族素数的个数
// Parameter: const FitInfo & fitInfo
// Returns:   UINT32
//************************************
UINT32 CalcMaxPrimerCount(const FitInfo &fitInfo, UINT32 &maxFitIncNum, UINT32 &maxFitTimes)
{
    UINT32 maxPrimerCount = 0;
    UINT32 currPrimerCount = 1;
    UINT32 fitCount = fitInfo.IncNums.size();
    UINT32 currNum;
    UINT32 fitIndex;
    UINT32 fitIncTimes;
    UINT32 fitIncCount;
    UINT32 fitIncNum;

    for(fitIndex = 0; fitIndex < fitCount; ++fitIndex)
    {
        currPrimerCount = 1;    // 初始化为1,因为fitInfo.Num已经是素数了
        currNum = fitInfo.Num;
        fitIncNum = fitInfo.IncNums[fitIndex];
        fitIncTimes = fitInfo.MaxIncTimes[fitIndex];

        for(fitIncCount = 0; fitIncCount < fitIncTimes; ++fitIncCount)
        {
            currNum += fitIncNum;
            if(MoonMath::IsPrimer(currNum))
            {
                ++currPrimerCount;

                if(currPrimerCount > maxPrimerCount)
                {
                    maxFitIncNum = fitIncNum;
                    maxFitTimes = fitIncTimes;
                    maxPrimerCount = currPrimerCount;
                }
            }
        }
    }

    return maxPrimerCount;
}

void TestFun1()
{
    FitInfo fitInfo;
    GetNotAdjacentFitInfo(100, fitInfo, 8);
    cout << "Test OK!" << endl;
}

void F1()
{
    cout << "void F1()" << endl;

    // TestFun1();

    DetailPrinter detailPrinter;
    detailPrinter.Start();

    /*********************************算法开始*******************************/
    const UINT32 FAMILY_PRIMER_COUNT = 6;       // 素数族中素数个数

    FitInfo fitInfo;
    UINT32 maxFitIncNum;
    UINT32 maxFitTimes;

    for(UINT32 num = 3;; num += 2)
    {
        if(MoonMath::IsPrimer(num))
        {
            GetNotAdjacentFitInfo(num, fitInfo, FAMILY_PRIMER_COUNT);
            if(CalcMaxPrimerCount(fitInfo, maxFitIncNum, maxFitTimes) >= FAMILY_PRIMER_COUNT)
            {
                break;
            }
        }
    }

    cout << "拥有至少" << FAMILY_PRIMER_COUNT << "个素数的素数族中最小的素数为"
            << fitInfo.Num << endl
            << "素数族其他成员为:";

    UINT32 primer = fitInfo.Num;
    for(UINT32 i = 0; i < maxFitTimes; ++i)
    {
        primer += maxFitIncNum;
        if(MoonMath::IsPrimer(primer))
        {
            cout << primer << " ";
        }
    }

    cout << endl;

    /*********************************算法结束*******************************/

    detailPrinter.End();
}

//主函数
int main()
{
    F1();
    return 0;
}

/*
void F1()
拥有至少6个素数的素数族中最小的素数为13
素数族其他成员为:23 43 53 73 83
Total Milliseconds is 4.50833

By GodMoon
Sun Mar 24 21:44:13 2013

void F1()
拥有至少7个素数的素数族中最小的素数为56003
素数族其他成员为:56113 56333 56443 56663 56773 56993
Total Milliseconds is 481.138

By GodMoon
Sun Mar 24 21:43:49 2013

void F1()
拥有至少8个素数的素数族中最小的素数为121313
素数族其他成员为:222323 323333 424343 525353 626363 828383 929393
Total Milliseconds is 1023.6

By GodMoon
Sun Mar 24 21:41:17 2013
*/


你可能感兴趣的:(【C/C++】,【ProjectEuler】)