Program to find the last digit of X in base Y
Last Updated :
20 Dec, 2022
Given a positive integer X and Y, the task is to find the last digit of X in the given base Y.
Examples:
Input: X = 10, Y = 7
Output: 3
10 is 13 in base 9 with last digit 3
Input: X = 55, Y = 3
Output: 1
55 is 3 in base 601 with last digit 1
Approach:
- When we try to convert X into the base Y
- We repeatedly divide X by base Y and store the remainder.
- So final result comprises of the remainders in the order of division steps.
- Lets say the remainder of division step 1 is p, step 2 is q, step 3 is r
- Then the resultant number in base Y will be rqp
- And the last digit will be p
- Therefore, we just need to find the first remainder of X when divided by Y to get the last digit in X in base Y.
last digit = X % Y
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void last_digit( int X, int Y)
{
cout << X % Y;
}
int main()
{
int X = 55, Y = 3;
last_digit(X, Y);
return 0;
}
|
Java
import java.io.*;
public class GFG
{
static void last_digit( int X, int Y)
{
System.out.print(X % Y);
}
public static void main(String []args)
{
int X = 55 , Y = 3 ;
last_digit(X, Y);
}
}
|
Python3
def last_digit(X, Y) :
print (X % Y);
if __name__ = = "__main__" :
X = 55 ; Y = 3 ;
last_digit(X, Y);
|
C#
using System;
class GFG
{
static void last_digit( int X, int Y)
{
Console.Write(X % Y);
}
public static void Main(String []args)
{
int X = 55, Y = 3;
last_digit(X, Y);
}
}
|
PHP
<?php
function last_digit( $X , $Y ){
echo ( $X % $Y );
}
$X = 55;
$Y = 3;
last_digit( $X , $Y );
?>
|
Javascript
<script>
function last_digit(X, Y)
{
document.write(X % Y);
}
var X = 55, Y = 3;
last_digit(X, Y);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...