Project Euler Problem 62 (C++和Python)

探讨了寻找最小立方数的问题,该立方数恰好有五个其数字排列也是立方数的变位词。通过C++和Python代码实现了算法,展示了如何通过比较数字排列来识别立方数的变位词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem 62 : Cubic permutations

The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.

Find the smallest cube for which exactly five permutations of its digits are cube.

C++ 代码 (如果打开编译开关 CPP_11,则要C+11编译器支持)

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <cmath>
#include <map>
#include <algorithm>
#include <cassert>
#include <ctime>
    
using namespace std;

#define CPP_11
//#define UNIT_TEST

typedef struct CubicPermutation
{
    int       number;
    long long cube; // number*number*number = cube
    string    digits;
} CubicPermutation;
    
class PE0062
{
private:
    string getDigitsString(long long number);
    bool checkCubicPermutations(map<string, int>& cubicPermu_mp,
                                vector<CubicPermutation>& cubicPermu,
                                long long& smallest_cube,
                                const int max_permutations);
public:
    long long findSmallestCube(const int max_permutations, 
                               int range_start, int range_end);
};
    
string PE0062::getDigitsString(long long number)
{
#ifndef CPP_11
    vector<int> digit_vec;

    while (number > 0)
    {
        digit_vec.push_back(number % 10);  // 197 => digits: 7, 9, 1
        number /= 10;
    }

    sort(digit_vec.begin(), digit_vec.end());

    vector<int>::iterator iter;
    string digits_str(digit_vec.begin(), digit_vec.end());

    for (unsigned int i = 0; i < digit_vec.size(); i++)
    {
        digits_str[i] = (char)(digit_vec[i] + '0');
    }

#else
    string digits_str = to_string(number);     // C++ 11
    sort(digits_str.begin(), digits_str.end());
#endif

    return digits_str;
}
    
bool PE0062::checkCubicPermutations(map<string, int>& cubicPermu_mp, 
                                    vector<CubicPermutation>& cubicPermu, 
                                    long long& smallest_cube,
                                    const int max_permutations)
{
    map<string, int>::iterator iter;

    for (iter = cubicPermu_mp.begin(); iter != cubicPermu_mp.end(); iter++)
    {
        if (max_permutations == iter->second)
        {
            vector<CubicPermutation>::iterator iter1;
            int number_of_Permutations = 0;
            for (iter1 = cubicPermu.begin(); iter1 != cubicPermu.end(); iter1++)
            {
                if (iter1->digits == iter->first)
                {
                    if (0 == smallest_cube)
                    {
                        smallest_cube = iter1->cube;
                    }
#ifdef UNIT_TEST
                    cout << iter1->cube << " (" << iter1->number << "^3)"<<endl;
#endif
                    number_of_Permutations++;
                    if (max_permutations == number_of_Permutations)
                    {
                        break;
                    }
                }
            }
            return true;
        }
    }
    return false;
}
    
long long PE0062::findSmallestCube(const int max_permutations, 
                                   int range_start, int range_end)
{
    vector<CubicPermutation>cubicPermu;
    map<string, int>cubicPermu_mp;
    CubicPermutation cp;

    for (long long number = range_start; number < range_end; number++)
    {
        cp.number = (int)number;
        cp.cube   = number * number*number;
        cp.digits = getDigitsString(cp.cube);
    
        cubicPermu.push_back(cp);
        cubicPermu_mp[cp.digits]++;
    }

    long long smallest_cube = 0;
    if (true == checkCubicPermutations(cubicPermu_mp, cubicPermu,
                                       smallest_cube, max_permutations))
    {
        return smallest_cube;
    }

    return 0;
}

int main()
{
#ifdef UNIT_TEST
    clock_t start = clock();
#endif

    PE0062 pe0062;

    assert(41063625 == pe0062.findSmallestCube(3, 100, 1000));

    const int max_permutations = 5;
    long long smallest_cube = pe0062.findSmallestCube(max_permutations,
                                                      406, 10000);

    cout << "The smallest cube for which exactly " << max_permutations;
    cout << " permutations of its digits are cube is ";
    cout << smallest_cube << "." << endl;

#ifdef UNIT_TEST
    clock_t finish = clock();
    double duration = (double)(finish - start) / CLOCKS_PER_SEC;
    cout << "C/C++ running time: " << duration << " seconds" << endl;
#endif
    return 0;
}

Python 代码

def checkCubicPermutations(cubicPermu_dict, cubicPermu_list, max_permutations):
    smallest_cube = 0
    for key, value in cubicPermu_dict.items():
        if value == max_permutations:
            number_of_Permutations = 0
            for cp in cubicPermu_list:
                if cp[2] == key:
                    if 0 == smallest_cube:
                        smallest_cube = cp[1]
                    print(cp[1], " (%d^3)" % cp[0])
                    number_of_Permutations += 1
                    if max_permutations == number_of_Permutations:
                        break
            return smallest_cube
    return 0
    
def findSmallestCube(max_permutations, range_start, range_end):
    cubicPermu_list = []
    cubicPermu_dict = {}
    for number in range(range_start, range_end):
        cube = number*number*number
        # cube_str = str(cube)
        # str_list = list(cube_str)
        # str_list.sort()
        # digits_str = ''.join(str_list)
        digits_str = ''.join((lambda x:(x.sort(),x)[1])(list(str(cube))))
        cubicPermu_list += [[ number, cube, digits_str ]]
        if digits_str in cubicPermu_dict.keys():
            cubicPermu_dict[digits_str] += 1
        else:
            cubicPermu_dict[digits_str] = 1
    
    smallest_cube = checkCubicPermutations(cubicPermu_dict,\
                                           cubicPermu_list, max_permutations)
    return smallest_cube

def main():
    assert 41063625 == findSmallestCube(3, 100, 1000)
    
    max_permutations = 5
    smallest_cube = findSmallestCube(max_permutations, 406, 10000)

    print("The smallest cube for which exactly %d" % max_permutations,end='')
    print(" permutations of its digits are cube is %d." % smallest_cube)

if  __name__ == '__main__':
    main()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值