0

I have written a simple tail recursive modular exponentiation function like this :

#include <bits/stdc++.h>
using namespace std;
#define mod (1000000000+7)
#define ll long long

ll modexp(ll x,ll n,ll res=1){
    if(n==0) return res;
    return modexp(x, n-1,(x % mod *res % mod) % mod);
} 
int main(){
    cout<<modexp(2,100000);
}

It is not running in my pc. I've tried in sublime with FastOlympicCoding which doesn't print anything. Then I tried using terminal :

PS C:\Users\User\Desktop\cpcpp> g++ test.cpp -o test.exe
PS C:\Users\User\Desktop\cpcpp> .\test.exe
PS C:\Users\User\Desktop\cpcpp>

This time it compiles but prints nothing. Then I tried in online ides like ideone, codechef. There it compiles and runs, for example: Ideone.

Then what is the problem in my native device?

I'm using Windows 10, GCC 12 with posix ...

akib35
  • 3
  • 3
  • Try to flush the output buffer `cout< – 273K Aug 04 '22 at 01:14
  • See also [Why should I not #include ?](https://stackoverflow.com/q/31816095/3422102) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/364696) (though for short exercises `using namespace std;` doesn't hurt) – David C. Rankin Aug 04 '22 at 01:17
  • @273K Still it's not working – akib35 Aug 04 '22 at 01:21
  • @DavidC.Rankin I've tried with `std::cout< – akib35 Aug 04 '22 at 01:26
  • 1
    I used `std::cout << modexp(2,100000) << '\n';` (note spacing to help older eyes...) and code ran fine. Output `607723520` (no clue if that is the correct output, but no problem producing it) `std::endl` would work as well. You can also have a look at [C++: “std::endl” vs “\n”](https://stackoverflow.com/questions/213907/c-stdendl-vs-n) for the difference. – David C. Rankin Aug 04 '22 at 01:29
  • That might be correct. Online ides prints something like that. IDK, what's the problem with my device. – akib35 Aug 04 '22 at 01:33
  • You might get stack overflow. Try to enable optimizations (incl. tail recursion) `g++ -O2 test.cpp -o test.exe` – 273K Aug 04 '22 at 01:37
  • 1
    Unlike some other languages (like Scheme), the C++ language does not mandate tail recursion. – Raymond Chen Aug 04 '22 at 02:21
  • You should use the *square and multiply* algorithm to keep the recursion depth down. It's also worlds faster. Or use a loop. – Goswin von Brederlow Aug 05 '22 at 08:53

0 Answers0