Given two positive integers X and Y, the task is to find the MSB of X, in the given base Y.
Examples:
Input: X = 55, Y = 3
Output: 2
Explanation:
55 is 2001 in base 3 with first digit as 2.
Input: X = 123, Y = 10
Output: 1
Explanation:
123 is 123 in base 10 with first digit 1.
Approach: Let the task to find 1st digit of X = 1234 in base Y = 10, So to get First digit = 1:
Divide 1234 by 1000
= X / 103
= X / 10Number of Digits in X – 1
= X / 10log(X) / log(10) (which is for base 10)
For any other base, we can replace 10 with Y. Therefore, we can calculate the first digit of a number X in base Y by using the formula:
X / Y(log(X)/log(Y))
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void first_digit( int x, int y)
{
int length = log (x) / log (y) + 1;
int first_digit = x / pow (y, length - 1);
cout << first_digit;
}
int main()
{
int X = 55, Y = 3;
first_digit(X, Y);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void first_digit( int x, int y)
{
int length = ( int )(Math.log(x) /
Math.log(y) + 1 );
int first_digit = ( int )(x / Math.pow(y,
length - 1 ));
System.out.println(first_digit);
}
public static void main(String args[])
{
int X = 55 , Y = 3 ;
first_digit(X, Y);
}
}
|
Python3
import math
def first_digit(x, y):
length = int (math.log(x) /
math.log(y) + 1 )
first_digit = x / math. pow (y, length - 1 )
print ( int (first_digit))
X = 55
Y = 3
first_digit(X, Y)
|
C#
using System;
class GFG{
static void first_digit( int x, int y)
{
int length = ( int )(Math.Log(x) /
Math.Log(y) + 1);
int first_digit = ( int )(x / Math.Pow(y,
length - 1));
Console.Write(first_digit);
}
public static void Main()
{
int X = 55, Y = 3;
first_digit(X, Y);
}
}
|
Javascript
<script>
function first_digit(x, y)
{
var length = parseInt(Math.log(x) / Math.log(y)) + 1;
var first_digit = parseInt(x / Math.pow(y, length - 1));
document.write( first_digit);
}
var X = 55, Y = 3;
first_digit(X, Y);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)