Search code examples
c++g++clangc++17

why two different compilers are giving two different results?


Problem is to find the last digit of the number (1358)^n. I've used the same method in c++ with two different compilers but the results are different in both the compilers on codeforces.

Compilers: clang c++17 Diagnostics(code accepted) but with GNU G++17 verdict is wrong_answer.

I'm not getting where the problem is, and why the results are different for both the compilers?

n = [0, 1000000000]

Test cases: 1000000000, 32, 33, 36

correct answer: 6, 6, 8, 6

but with GNU Compiler: 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;
}

Solution

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

    There is no need to use floating point to solve this problem. You seem to have realised that the last digit follows the repeating pattern of 8, 4, 2, 6. To find which element of this pattern you are using you can simply use 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;
    }