0

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;
}
lokesh bihani
  • 89
  • 1
  • 9
  • 2
    In your question you wrote 4 test inputs (1000000000, 32, 33, 36) but only 3 outputs (expected 6, 6, 8 and actually got 1, 1, 8). Please also add the platform (CPU architecture) and compiling options to help people finding an answer. – Hero Wanders Jan 12 '21 at 06:52
  • Should your while loop just be something like `n = n%4; if (n==0) n =4;`? I imagine your code is failing due to floating point rounding errors – Alan Birtles Jan 12 '21 at 07:44
  • @HeroWanders thanks for pointing that out! I've updated the results now. – lokesh bihani Jan 13 '21 at 10:42

1 Answers1

2

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;
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60