📌  相关文章
📜  程序在基Y中查找X的最后一位

📅  最后修改于: 2021-05-07 18:42:31             🧑  作者: Mango

给定正整数X和Y,任务是在给定的基数Y中找到X的最后一位。

例子:

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

方法:

  • 当我们尝试将X转换为基Y时
  • 我们反复将X除以基数Y,然后存储余数。
  • 因此,最终结果按划分步骤的顺序包含了余数。
  • 假设除法步骤1的余数是p,步骤2是q,步骤3是r
  • 那么以Y为底的结果数将为rqp
  • 最后一位是p
  • 因此,我们只需要找到X除以Y的第一个余数,就可以得到X以基Y的最后一位。
last digit = X % Y

下面是上述方法的实现:

C++
// C++ Program to find
// the last digit of X in base Y
 
#include 
using namespace std;
 
// Function to find the last
// digit of X in base Y
void last_digit(int X, int Y)
{
    cout << X % Y;
}
 
// Driver code
int main()
{
    int X = 55, Y = 3;
    last_digit(X, Y);
    return 0;
}


Java
// Java Program to find
// the last digit of X in base Y
class GFG
{
 
// Function to find the last
// digit of X in base Y
static void last_digit(int X, int Y)
{
    System.out.print(X % Y);
}
 
// Driver code
public static void main(String []args)
{
    int X = 55, Y = 3;
    last_digit(X, Y);
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 Program to find
# the last digit of X in base Y
 
# Function to find the last
# digit of X in base Y
def last_digit(X, Y) :
 
    print(X % Y);
 
# Driver code
if __name__ == "__main__" :
 
    X = 55; Y = 3;
    last_digit(X, Y);
 
# This code is contributed
# by AnkitRai01


C#
// C# Program to find the last digit
// of X in base Y
using System;
 
class GFG
{
 
// Function to find the last
// digit of X in base Y
static void last_digit(int X, int Y)
{
    Console.Write(X % Y);
}
 
// Driver code
public static void Main(String []args)
{
    int X = 55, Y = 3;
    last_digit(X, Y);
}
}
 
// This code is contributed by Rajput-Ji


PHP


Javascript


输出:
1

时间复杂度: O(1)