[英]My C++ program behaves strange with wrong output?
I want to view all solution for: X^12≡1(mod27) So I wrote the following C++ program which outputs only 1 even though 8 and 10 are possible values for x too.我想查看以下所有解决方案: X^12≡1(mod27) 所以我编写了以下 C++ 程序,即使 8 和 10 也是 x 的可能值,它也只输出 1。
Why is that?这是为什么?
#include <iostream>
#include <cmath>
int main() {
for (int i = 0; i <= 2700000; ++i) {
if (int(pow(i, 12))% 27 == 1) {
std::cout << i << std::endl;
}
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
The inbuild pow()
function is not capable of handling so large number.内置
pow()
function 无法处理如此大的数字。 Rather we have to use custom function to achieve that.相反,我们必须使用自定义 function 来实现这一点。
Here it is这里是
#include <iostream>
#include <cmath>
long long binpow(long long a, long long b, long long m) {
a %= m;
long long res = 1;
while (b > 0) {
if (b & 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
int main() {
for (int i = 0; i <= 2700000; ++i) {
if (binpow(i, 12, 27) == 1) {
std::cout << i << std::endl;
}
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
You can read more about that function from here: https://cp-algorithms.com/algebra/binary-exp.html您可以从此处阅读有关 function 的更多信息: https://cp-algorithms.com/algebra/binary-exp.html
Oh, that's because you're using int
s to calculate 12th powers, which are very large numbers.哦,那是因为您使用
int
s 来计算 12 次方,这是非常大的数字。 Int can only store numbers up to 2147483647, so use long long ints instead which can be much larger. Int 最多只能存储 2147483647 的数字,因此请使用 long long int 代替,它可以更大。
I rewrote your code and got this output: 1 8 10 17 19 26 28我重写了你的代码,得到了这个 output: 1 8 10 17 19 26 28
#include <iostream>
#include <cmath>
int main()
{
for (int i = 0; i <= 2700000; ++i)
{
long long int power = pow(i, 12);
int mod = power % 27;
if (mod == 1)
std::cout << i << std::endl;
}
std::cin.get();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.