📌  相关文章
📜  查找阶乘的最后一位数字

📅  最后修改于: 2021-05-06 17:43:53             🧑  作者: Mango

给定数字n,我们需要找到阶乘n的最后一位。

一个幼稚的解决方案是首先计算事实= n !,然后通过执行事实%10返回结果的最后一位。此解决方案效率低下,并且即使n的值稍大,也会导致整数溢出。

一个有效的解决方案基于以下观察结果:5之后的所有阶乘都以0作为最后一位数字。

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
…………..

C++
// C++ program to find last digit in
// factorial n.
#include 
using namespace std;
 
int lastDigitFactorial(unsigned int n)
{
   // Explicitly handle all numbers
   // less than or equal to 4
   if (n == 0) return 1;
   else if (n <= 2) return n;
   else if (n == 3) return 6;
   else if (n == 4) return 4;
   
   // For all numbers greater than 4
   // the last digit is 0
   else return 0;
}
 
int main() {
 
    cout<


Java
// Java program to find last 
// digit in factorial n.
import java.io.*;
import java.util.*;
 
class GFG {
     
static int lastDigitFactorial(int n)
{
     
    // Explicitly handle all numbers
    // less than or equal to 4
    if (n == 0) return 1;
    else if (n <= 2) return n;
    else if (n == 3) return 6;
    else if (n == 4) return 4;
     
    // For all numbers greater than
    // 4 the last digit is 0
    else return 0;
}
 
// Driver code
public static void main(String[] args)
{
    System.out.println(lastDigitFactorial(6));
}
}
 
// This code is contributed by coder001


Python3
# Python3 program to find last digit in
# factorial n.
 
def lastDigitFactorial(n):
     
    # Explicitly handle all numbers
    # less than or equal to 4
    if (n == 0): return 1
    elif (n <= 2): return n
    elif (n == 3): return 6
    elif (n == 4): return 4
     
    # For all numbers greater than 4
    # the last digit is 0
    else: return 0
 
print(lastDigitFactorial(6))
 
# This code is contributed by divyeshrabadiya07


C#
// C# program to find last
// digit in factorial n.
using System;
class GFG{
     
static int lastDigitFactorial(int n)
{
     
    // Explicitly handle all numbers
    // less than or equal to 4
    if (n == 0) return 1;
    else if (n <= 2) return n;
    else if (n == 3) return 6;
    else if (n == 4) return 4;
     
    // For all numbers greater than
    // 4 the last digit is 0
    else return 0;
}
 
// Driver code
public static void Main(string[] args)
{
    Console.Write(lastDigitFactorial(6));
}
}
 
// This code is contributed by rutvik_56


Javascript


输出:
0

时间复杂度:O(1)
辅助空间:O(1)

现在尝试以下问题

1)阶乘中的最后一个非零数字
2)计算阶乘中的零
3)阶乘的第一个数字