簡體   English   中英

優化代碼以找到給定數量N的階乘的單位數

[英]Optimising code to find the unit digit of factorial of given number N

我在競賽中嘗試了一個問題,其確切陳述是這樣的:

Given a number N. The task is to find the unit digit of factorial of given 
number N.

Input:
First line of input contains number of testcases T. For each testcase, there 
will be a single line containing N.

Output:
For each testcase, print the unit digit of factorial of N.

Constraints:
1 <= T <= 1000
1 <= N <= 1018 

並提出以下代碼:

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) throws IOException{
     BufferedReader reader =  
               new BufferedReader(new InputStreamReader(System.in)); 
    int cases = Integer.parseInt(reader.readLine());
    int i=0;
    while(i<cases){
        fact(Integer.parseInt(reader.readLine()));i++;
    }
}

static void fact(int num){
    int j,fact=1;     
    for(j=1;j<=num;j++){    
        fact=fact*j;    
        }  
        System.out.println(fact%10);
   }
}

當使用自定義輸入執行時,它會提供正確的輸出,但是當嘗試所有測試用例時,它會給出: “超出時間限制。優化代碼” 我試圖使用bufferedReader而不是Scanner類,但沒有效果。 我無法找到如何進一步優化此代碼。 有什么我想念的嗎?

BufferedReaderScanner之間的區別可能在這里不明顯。 如果您對代碼進行基准測試,您可能會發現最重要的部分是因子計算。 另外,我想不出更快的計算方法,但這里你可能沒有必要。

讓我們來看看前幾個因子:

  • 0! = 1 - >單位數為1
  • 1! = 1 - >單位數為1
  • 2! = 2 - >單位數為2
  • 3! = 6 - >單位數為6
  • 4! = 24 - >單位數為4
  • 5! = 120 - >單位數為0

任何6或更大的階乘都是一些自然整數乘以5!,即120.所以,無論它們是什么,單位數字都是0.使用如此小的數據集,你可以創建一個全部的緩存選項而不是每次計算階乘。 例如:

// The index is the factorial to be calculated, the value is the unit digit:
private static final int[] UNITS = new int[] {1, 1, 2, 6, 4};

private static void fact(int f) {
    int unit = 0;
    if (f <= 4) {
        unit = UNITS[f];
    }
    System.out.println(unit);
}

您不必為此問題計算因子。 對於n > 4fact(n)的單位數將為0 (我會為其他可能的輸入做一個小桌子。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM