gpt4 book ai didi

c++ - 处理 double 时模运算符的使用

转载 作者:太空宇宙 更新时间:2023-11-04 04:01:14 32 4
gpt4 key购买 nike

我必须找到 ( 1+sqrt(3) )^n 的值,其中 n < 10^9。由于这个数字可能非常大,我们必须打印 ans%1000000007。我为此编写了以下函数。

double power(double x, int y)
{
double temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
{
if(y > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}

现在,我无法理解如何处理模数条件。有人可以帮忙吗。

最佳答案

你不能那样做。您可以使用 fmod,但由于无法准确表示 sqrt(3),您会得到大指数的虚假值。

我相当确信您实际上需要整数结果 ((1 + sqrt(3))^n + (1 - sqrt(3))^n),因此您应该使用整数数学,通过在每一步取模运算的平方求幂。比照。 this question

关于c++ - 处理 double 时模运算符的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11379645/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com