博客
关于我
poj1730 - Perfect Pth Powers(完全平方数)(水题)
阅读量:803 次
发布时间:2023-03-03

本文共 1256 字,大约阅读时间需要 4 分钟。

为了解决问题,我们需要找到最大的整数指数 ( p ),使得给定的整数 ( n ) 可以表示为某个整数 ( b ) 的 ( p ) 次方。具体来说,我们需要找到最大的 ( p ) 使得 ( n = b^p )。

解题思路

  • 问题分析:我们需要找到最大的 ( p ) 使得 ( n ) 是一个完全幂。完全幂包括平方数、立方数等等。
  • 遍历指数:我们从最大的可能指数开始遍历,具体从31开始,因为2^31已经接近整数范围的上限。
  • 精度控制:使用 pow 函数计算可能的 ( b ) 值时,由于 pow 返回的值可能有精度问题,我们需要对结果进行调整,避免丢失整数部分。
  • 处理负数:当 ( n ) 为负数时,我们需要考虑 ( b ) 的符号,确保 ( b^p ) 的结果为负数。
  • 代码实现

    #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;}

    代码解释

  • 输入处理:读取输入的整数 ( a )。
  • 正数处理:如果 ( a ) 为正数,从 ( p = 31 ) 开始递减,尝试每个 ( p )。
  • 计算 ( b ):使用 pow 计算 ( a ) 的 ( p ) 次方根,并加上0.1以避免精度丢失。
  • 验证结果:计算 ( b^p ) 的值,检查是否等于 ( a )。
  • 输出结果:找到最大的 ( p ) 后输出。
  • 这种方法确保了我们能够高效地找到最大的 ( p ) 值,同时处理了可能的负数情况。

    转载地址:http://ydxfk.baihongyu.com/

    你可能感兴趣的文章
    python pandas TimeStamps到夏令时的本地时间字符串
    查看>>
    Python pandas 数据清洗与数据绘图实战
    查看>>
    Python Pandas 用顶行替换标题
    查看>>
    Python pandas 通过 dt 访问器有效地将日期时间转换为时间戳
    查看>>
    Python Pandas-从DataFrame按类别绘制多个条形图
    查看>>
    Python Pandas:每月或每周拆分 TimeSerie
    查看>>
    python pandas中融化的对面
    查看>>
    python pandas从时间序列中提取唯一日期
    查看>>
    Python Pypi 修改 国内源(以豆瓣源为例)
    查看>>
    Python PyQt5 将不再显示此消息复选框添加到 QMessageBox
    查看>>
    Python PyQt5:如何使用 PyQt5 显示错误消息
    查看>>
    Python PYSFTP-以字符串/文本形式传递私钥,而不是传递文件路径
    查看>>
    Python pytest 面试题!
    查看>>
    Python pytz 时区函数返回一个相差 9 分钟的时区
    查看>>
    python rabbitmq实现简单/持久/广播/组播/topic/rpc消息异步发送可配置Django
    查看>>
    Python random和json模块
    查看>>
    Python random模块seed理解
    查看>>
    python range()函数
    查看>>
    Python rdflib可传递查询
    查看>>
    python redis 集群_python 搭建redis集群
    查看>>