2017-03-12 22 views
-4

我有兩個以下版本的實現,他們爲什麼返回不同的結果?返回不同的結果來找到Factorial Trailing Zero

陳述問題

給定一個整數n,返回在正尾隨零的數目!在Java中

源代碼,

public class TrailingZero { 

    public static int trailingZeroes(int n) { 
     int result = 0; 
     int base = 5; 
     while (n/base > 0) { 
      result += n/base; 
      base *= 5; 
     } 

     return result; 
    } 

    public static int trailingZeroesV2(int n) { 
     return n == 0 ? 0 : n/5 + trailingZeroes(n/5); 
    } 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     System.out.println(trailingZeroes(1808548329)); 
     System.out.println(trailingZeroesV2(1808548329)); 
    } 

} 
+3

歡迎回到Stack Overflow!尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須在問題本身中包含所需的行爲,特定的問題或錯誤以及必要的最短代碼**。沒有明確問題陳述的問題對其他讀者無益。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

+1

我認爲這個問題想要你返回n階乘的尾隨零的數量。 –

+2

在第二次遞歸調用應該是'trailingZeroesV2';一個錯字,是不是。 –

回答

1

base變得乘以5在第二個版本迷路了。

public static int trailingZeroesV2(int n) { 
    return trailingZeroesV2(n, 5); 
} 

private static int trailingZeroesRec(int n, int base) { 
    return n == 0 ? 0 : n/base + trailingZeroesRec(n/5, base * 5); 
} 

(通常遞歸函數使用一個額外的參數)

兩個版本我留給你的別出心裁的正確性。 它明顯地使用因子5中的因子數目至少具有相同的因子2的數目。所以10的因子可以這樣確定。

然而,我會考慮% 5,模5。但我不會認真鑽研你的算法。

+1

這應該是'n/5 + trailingZeroesRec(n/5,base * 5)' – user1952500

+0

謝謝Joop,你的意思是第一個版本是正確的? –

+0

順便說一句,喬普,標記你的答案作爲答案,我開始一個新的職位,使我的問題更加清晰,我們可以繼續在這裏討論=> http://stackoverflow.com/questions/42756140/inconsistent-results-當-finding-factorial-trailing-zero –