+ 1
The code below calculates a^b (up to 1000000 digits results), any ideea to improve it, maybe make it faster?
#include <iostream> using namespace std; int v[1000000]; int main(){ int n,x,aux; cin >>x>>n; v[v[0]=1]=1; for(int k=1;k<=n;++k) { int t = 0; for(int i=1;i<=v[0];++i) { aux=v[i]*x+t; v[i]=aux%10; t=aux/10; } while(t) { v[++v[0]]=t%10; t/=10; } } for(int i=v[0];i>0;--i) cout<<v[i]; return 0; }
7 Réponses
+ 12
This is unnecessarily complex... unless there were conditions that you needed to fulfill, idk. I just wrote this something, you may check it out if it works the way you want it to. It handles pow 0 and result goes up to 16 digits.
#include <iostream>
using namespace std;
int main() {
int base;
int pow;
long long int result = 1;
cin >> base;
cin >> pow;
for (int i = 0; i < pow; i++)
{
result *= base;
}
cout << result;
return 0;
}
+ 11
@Catalin My sincere apologies, I see your point now. I'll get back with a legit opinion.
+ 4
You could also take advantage of the fast exponentiation algorithm (recursive): for a^b,
- if b is 0, return 1
- if b is even, return (a*a)^(b/2) (recursive call)
- if b is odd, return a*(a^(b-1)) (recursive call)
You may take a look at https://code.sololearn.com/cNlG5g0X9tjV/?ref=app
[EDIT] The actual code is written in Python, but it can be ported to C++ or Java as well.
+ 1
Hatsi Rei well the whole point it is that it can calculate very large numbers, larger than predefined types of c++, but thanks for trying
+ 1
Thank you Alvaro, I'm going to try it
+ 1
@Hatsi Rei, I quess you saw it's up to 1000000 digits, not the number 1000000
+ 1
@Hatsy Rei, no need for to apologize my friend, always thankful to see someone's trying to help me, you rock