java单位数_java – 优化代码以查找给定数量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
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類,但沒有效果.我無法找到如何進一步優化此代碼.有什么我想念的嗎?
解決方法:
BufferedReader和Scanner之間的區別可能在這里不明顯.如果您對代碼進行基準測試,您可能會發現最重要的部分是因子計算.另外,我想不出更快的計算方法,但這里你可能沒有必要.
讓我們來看看前幾個因子:
> 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);
}
標簽:java,algorithm,performance,factorial
來源: https://codeday.me/bug/20190716/1473805.html
總結
以上是生活随笔為你收集整理的java单位数_java – 优化代码以查找给定数量N的阶乘的单位数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 绘制颜色渐变三角形
- 下一篇: 绘制颜色渐变矩形函数