+ 9
[ASSIGNMENT] To calculate the digit at unit's place of a exponential number.
You just have to give base and power as input and the program should print the digit at unit's place example= 3^4 here 3 is base and 4 is the power. The code should print 1.(3^4=81) any language is welcome :D Happy coding. https://code.sololearn.com/cj7MPEztD1si/?ref=app
13 Answers
+ 8
python: pow(x,n,10) ( power modulo 10)
+ 5
Ali Zhussupov I have changed the code.
+ 5
Similar to Ali Zhussupov's Solution
https://code.sololearn.com/c7YVBa0Tk8nw/?ref=app
+ 4
https://code.sololearn.com/cAbBpR4sZaI5/?ref=app
+ 4
If O(n) complexity is enough for you, heres C/C++ solution:
int base, power, ans = 1;
cin>>base>>power;
for (int i = 0; i < power; i++)
ans = (ans * base) % 10;
cout<<ans;
Unlike the other solutions mentioned here, this solution keeps only the last digit as an intermediate calculation.
It also can be improved using binary exponentiation, which results in O(log n) complexity.
+ 3
@Swapnil More, your solution will fail if base^power wont fit ‘int’ type.
Yet, the same python solution by @VcC will work fine due to built in capabilities
+ 3
Ali Zhussupov thanks😃😅
+ 3
Ali Zhussupov I made the attached code so that i can input high base and powers and still get the answer at same time.O(1) complexity probably.
+ 2
@Swapnil More, I guess overkill isn’t in your vocabulary 😅
Just joking :) great job!👍
+ 2
Void Skeleton, if base^power is too big it will fail
+ 1
Abnishek Singh Negi, yes, your solution makes it in constant time, but to me, the implementation is too big and inflexible. Though, it can be necessary depending on input conditions.
So its for everyone to decide how to solve the problem, I just suggested my version :)
+ 1
Java: Math.pow(base, power)%10
Isn’t it very simple?