本文共 1256 字,大约阅读时间需要 4 分钟。
为了解决问题,我们需要找到最大的整数指数 ( p ),使得给定的整数 ( n ) 可以表示为某个整数 ( b ) 的 ( p ) 次方。具体来说,我们需要找到最大的 ( p ) 使得 ( n = b^p )。
pow 函数计算可能的 ( b ) 值时,由于 pow 返回的值可能有精度问题,我们需要对结果进行调整,避免丢失整数部分。#include#include #include #include #include #include #include #include #include using namespace std;int main() { int a; while (cin >> a && a) { if (a > 0) { for (int p = 31; p >= 1; --p) { int b = static_cast (pow(a * 1.0, 1.0 / p) + 0.1); if (b <= 0) { continue; } int b_power = static_cast (pow(b * 1.0, p) + 0.1); if (b_power == a) { cout << p << endl; return 0; } } } else { for (int p = 31; p >= 1; --p) { int b = static_cast (pow(a * 1.0, 1.0 / p) + 0.1); if (b <= 0) { continue; } int b_power = static_cast (pow(b * 1.0, p) + 0.1); if (b_power == a) { cout << p << endl; return 0; } } } } return 0;}
pow 计算 ( a ) 的 ( p ) 次方根,并加上0.1以避免精度丢失。这种方法确保了我们能够高效地找到最大的 ( p ) 值,同时处理了可能的负数情况。
转载地址:http://ydxfk.baihongyu.com/