K-th digit in ‘a’ raised to power ‘b’
Given three numbers a, b and k, find k-th digit in ab from right side
Examples:
Input : a = 3, b = 3, k = 1
Output : 7
Explanation: 3^3 = 27 for k = 1. First digit is 7 in 27
Input : a = 5, b = 2, k = 2
Output : 2
Explanation: 5^2 = 25 for k = 2. First digit is 2 in 25
Method
1) Compute a^b
2) Iteratively remove the last digit until k-th digit is not meet
C++
#include <bits/stdc++.h>
using namespace std;
int kthdigit( int a, int b, int k)
{
int p = pow (a, b);
int count = 0;
while (p > 0 && count < k) {
int rem = p % 10;
count++;
if (count == k)
return rem;
p = p / 10;
}
return 0;
}
int main()
{
int a = 5, b = 2;
int k = 1;
cout << kthdigit(a, b, k);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
public class GfG {
public static int kthdigit( int a, int b, int k)
{
int p = ( int )Math.pow(a, b);
int count = 0 ;
while (p > 0 && count < k) {
int rem = p % 10 ;
count++;
if (count == k)
return rem;
p = p / 10 ;
}
return 0 ;
}
public static void main(String argc[]) {
int a = 5 , b = 2 ;
int k = 1 ;
System.out.println(kthdigit(a, b, k));
}
}
|
Python3
def kthdigit(a, b, k):
p = a * * b
count = 0
while (p > 0 and count < k):
rem = p % 10
count = count + 1
if (count = = k):
return rem
p = p / 10 ;
a = 5
b = 2
k = 1
ans = kthdigit(a, b, k)
print (ans)
|
C#
using System;
public class GfG {
public static int kthdigit( int a, int b, int k)
{
int p = ( int )Math.Pow(a, b);
int count = 0;
while (p > 0 && count < k) {
int rem = p % 10;
count++;
if (count == k)
return rem;
p = p / 10;
}
return 0;
}
public static void Main() {
int a = 5, b = 2;
int k = 1;
Console.WriteLine(kthdigit(a, b, k));
}
}
|
Javascript
<script>
function kthdigit(a, b, k)
{
let p = Math.pow(a, b);
let count = 0;
while (p > 0 && count < k) {
let rem = p % 10;
count++;
if (count == k)
return rem;
p = p / 10;
}
return 0;
}
let a = 5, b = 2;
let k = 1;
document.write(kthdigit(a, b, k));
</script>
|
PHP
<?php
function kthdigit( $a , $b , $k )
{
$p = pow( $a , $b );
$count = 0;
while ( $p > 0 and $count < $k )
{
$rem = $p % 10;
$count ++;
if ( $count == $k )
return $rem ;
$p = $p / 10;
}
return 0;
}
$a = 5;
$b = 2;
$k = 1;
echo kthdigit( $a , $b , $k );
?>
|
Output:
5
Time Complexity: O(log p)
Auxiliary Space: O(1)
How to avoid overflow?
We can find power under modulo 10sup>k to avoid overflow. After finding the power under modulo, we need to return first digit of the power.
Last Updated :
07 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...