为什么两个不同的编译器给出两个不同的结果?

why two different compilers are giving two different results?

问题是找到数字 (1358)^n 的最后一位。我在 c++ 中使用了相同的方法和两个不同的编译器,但结果在 codeforces 上的两个编译器中是不同的。

编译器:clang c++17 诊断(代码已接受)但 GNU G++17 的判决是 wrong_answer。

我不明白问题出在哪里,为什么两个编译器的结果不同?

n = [0, 1000000000]

测试用例:1000000000、32、33、36

正确答案:6、6、8、6

但使用 GNU 编译器:1、1、8、6

#include<bits/stdc++.h>
using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    double n; cin >> n;
    vector<long long> res{ 1, 8, 4, 2, 6 };
    if (n <= 4){
        cout << res[n] << "\n";
    }
    else{
        while (n > 4){
            double x = log10(n)/log10(2);
            n = (ceil(x) == floor(x))? 4 : n - pow(2, floor(x));
        }
        cout << res[n] << "\n";
    }
    return 0;
}

can't reproduce your problem but it is likely due to floating point rounding errors (see Is floating point math broken?).

不需要用浮点数来解决这个问题。您似乎已经意识到最后一位数字遵循 8、4、2、6 的重复模式。要查找您正在使用此模式的哪个元素,您只需使用 n % 4:

#include <iostream>
#include <vector>
#include <cmath>

int main() {
    for (int n : {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 32, 33, 36, 1000000000})
    {
        std::vector<int> res{ 1, 8, 4, 2, 6 };
        n = (n - 1) % 4 + 1;
        std::cout << res[n] << "\n";
    }
    return 0;
}