【发布时间】:2018-06-23 05:53:31
【问题描述】:
所以我应该找出 2^n(064 时程序失败。任何有关如何进行此操作的线索将不胜感激。
#include<stdio.h>
#include<math.h>
/* Iterative Function to calculate (x^y)%p in O(log y) */
int power(long long int x, long long int y, long long int p)
{
long long int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0) {
// If y is odd, multiply x with result
if (y & 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// C function to print last 10 digits of a^b
void printLastDigits(long long int a,long long int b)
{
long long int temp = pow(10,10);
// Calling modular exponentiation
temp = power(a, b, temp);
if (temp)
printf("%d",temp);
}
int main()
{
long long int n;
scanf("%d",&n);
printLastDigits(2,n);
return 0;
}
【问题讨论】:
-
这是对你观察能力的考验。您可能被期望找到模式(因为存在模式)并将您的知识应用于推断(因此您无需计算
2^n)。 -
使用 modpow 的想法可行,但是由于
x * x(和res * x)臭名昭著的“提前溢出”,你的 modpow 不起作用,在你有机会减少它之前p. -
@harold 那么有没有办法解决这个问题?
-
一种简单的方法是将 1 乘以 2,n 次,同时丢弃最后 10 位以上的数字。您还可以找到 2 的幂的最后 10 位数字中的每一个的模式,但它涉及进位.
-
对于
n <= 100求平方并不是那么关键,您可以轻松地乘以 2^20(最多 5 步,所以仍然非常快)而不会过早溢出