如何提取输出指定数字?如何移除BigInteger中的0?阶乘场景示例
Hey there! Let's break down your two questions clearly, since you're currently outputting full factorial values but need to target the last non-zero digit (plus you're curious about stripping zeros from BigIntegers):
1. Get the Last Non-Zero Digit of a Factorial (The Efficient Way)
Calculating the full factorial and then processing it is inefficient—especially for large n, since factorials grow extremely quickly. Instead, we can avoid generating the full value entirely by focusing on the factors that create trailing zeros and computing only what we need:
Key Insight:
Trailing zeros in a factorial come from pairs of factors 2 and 5. Since there are always more 2s than 5s in a factorial, we can count both, subtract the number of 5s from the number of 2s (to eliminate all 10s), then compute the product of the remaining digits (modded to keep numbers manageable) and multiply by the leftover 2s.
Example Code (Java):
public static int lastNonZeroDigitOfFactorial(int n) { int count2 = 0, count5 = 0; int result = 1; // Iterate through each number up to n for (int i = 1; i <= n; i++) { int num = i; // Count all factors of 2 in current number while (num % 2 == 0) { count2++; num /= 2; } // Count all factors of 5 in current number while (num % 5 == 0) { count5++; num /= 5; } // Multiply the remaining part of the number to result, mod 100000 to prevent overflow result = (result * (num % 100000)) % 100000; } // Remove the paired 2s and 5s (each pair makes a 10, which adds a trailing zero) int remaining2 = count2 - count5; for (int i = 0; i < remaining2; i++) { result = (result * 2) % 100000; } // Strip any remaining trailing zeros and return the last digit while (result % 10 == 0) { result /= 10; } return result % 10; }
2. Removing All Zeros from a BigInteger
If you really need to strip every zero from a BigInteger (note: this is not the best approach for getting the last non-zero digit of a factorial), you can convert it to a string, replace all "0" characters, then convert back to a BigInteger.
Example Code (Java):
import java.math.BigInteger; public static BigInteger removeAllZeros(BigInteger number) { if (number.equals(BigInteger.ZERO)) { return BigInteger.ZERO; } // Replace all zeros in the string representation String stripped = number.toString().replaceAll("0", ""); // Fallback in case all digits were zero (we checked for ZERO earlier, so this is safe) return stripped.isEmpty() ? BigInteger.ZERO : new BigInteger(stripped); }
Important Note:
Stripping all zeros from a full factorial is a waste of resources for your original goal. The first method above is far faster and uses way less memory, especially for large n.
内容的提问来源于stack exchange,提问作者waynekenoff

