Horje
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

Recommended Practice

Method 
1) Compute a^b 
2) Iteratively remove the last digit until k-th digit is not meet 

C++

<?php
// PHP program for finding
// k-th digit in a^b
 
// To compute k-th
// digit in a^b
function kthdigit($a, $b, $k)
{
     
    // computing a^b
    $p = pow($a, $b);
 
    $count = 0;
    while ($p > 0 and $count < $k)
    {
 
        // getting last digit
        $rem = $p % 10;
 
        // increasing count by 1
        $count++;
 
        // if current number is
        // required digit
        if ($count == $k)
            return $rem;
 
        // remove last digit
        $p = $p / 10;
    }
 
    return 0;
}
 
    // Driver Code
    $a = 5;
    $b = 2;
    $k = 1;
    echo kthdigit($a, $b, $k);
 
// This code is contributed by anuj_67.
?>

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.




Reffered: https://www.geeksforgeeks.org


Mathematical

Related
Check whether given three numbers are adjacent primes Check whether given three numbers are adjacent primes
Sum of square of first n odd numbers Sum of square of first n odd numbers
Sum of square of first n even numbers Sum of square of first n even numbers
Number of terms in Geometric Series with given conditions Number of terms in Geometric Series with given conditions
Palindromic Selfie Numbers Palindromic Selfie Numbers

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16