关于pow的精度问题,HDU6182

本文介绍了解决大整数幂运算中精度问题的方法,通过自定义幂运算函数替代标准库函数,成功解决了ACM数学题目的精度误差问题。

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


A Math Problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2714    Accepted Submission(s): 935


Problem Description
You are given a positive integer n, please count how many positive integers k satisfy kkn.
 

Input
There are no more than 50 test cases.

Each case only contains a positivse integer n in a line.

1n1018
 

Output
For each test case, output an integer indicates the number of positive integers k satisfy kkn in a line.
 

Sample Input

 
14
 

Sample Output

 
12


贴源代码,WA
#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
int main()
{
    long long n;
    int it = 50;
    while(it--)
    {
        while(cin >> n)
    {
        int i;
        for(i = 1; i <= n; i ++)
        {
            //cout<<"%%" << pow(i,i) << endl;
            if(floor(pow(i,i)) > n)
            {
                break;

            }

        }
        cout << i-1 << endl;
    }
    }
    return 0;
}

然后是AC之后的代码
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define LL long long

LL kpow(LL x,LL n)
{
    LL res=1;
    while(n>0)
    {
        if(n & 1)//如果n的末位是1,即判断是否是奇数
            res=(res*x);
        x=(x*x);
        n >>= 1;
    }
    return res;
}
int main()
{

    LL n;
    while(scanf("%lld",&n)!=EOF)
    {
        for(int k=15;k>=1;k--)
        {
            if(kpow(k,k)<=n)
            {
                printf("%d\n",k);
                break;
            }
        }
     }
    return 0;
}

因为直接使用pow函数会出现精度问题,特别是计算比较大的数字的时候,所以一般这种情况下需要自己来写一个pow来使用,困扰很久,再度感谢博主解惑,博主文章地址在第一行里面链接


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值