Created
December 23, 2012 06:15
-
-
Save daisy1754/4362274 to your computer and use it in GitHub Desktop.
Project Euler Problem 154
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
// Project Euler 154 | |
// 479742450 | |
// 59.7 seconds | |
public class Problem154 { | |
private static final int THT = 200000; // Two Hundred Thousand | |
private int[] numOf2FactorsInFactorial = new int[THT + 1]; | |
private int[] numOf5FactorsInFactorial = new int[THT + 1]; | |
public static void main(String args[]) { | |
Problem154 this_ = new Problem154(); | |
long startTimeMillis = System.currentTimeMillis(); | |
System.out.println(this_.solve()); | |
long durationMillis = System.currentTimeMillis() - startTimeMillis; | |
System.out.println(durationMillis / 1000 + "." | |
+ (durationMillis % 1000) / 100 + " seconds"); | |
} | |
public Problem154() { | |
Arrays.fill(numOf2FactorsInFactorial, -1); | |
Arrays.fill(numOf5FactorsInFactorial, -1); | |
} | |
private int solve() { | |
int answer = 0; | |
int numOf5FactorsInTHTFactorial = numOfPFactorsInFactorial(THT, 5); | |
int numOf2FactorsInTHTFactorial = numOfPFactorsInFactorial(THT, 2); | |
for (int a = 0; a <= THT / 3; a++) { | |
for (int b = a; b <= (THT - a) / 2; b++) { | |
int c = THT - a - b; | |
assert (a <= b); | |
assert (b <= c); | |
int numOf5Factors | |
= numOf5FactorsInTHTFactorial | |
- numOfPFactorsInFactorial(a, 5) | |
- numOfPFactorsInFactorial(b, 5) | |
- numOfPFactorsInFactorial(c, 5); | |
if (numOf5Factors >= 12) { | |
int numOf2Factors | |
= numOf2FactorsInTHTFactorial | |
- numOfPFactorsInFactorial(a, 2) | |
- numOfPFactorsInFactorial(b, 2) | |
- numOfPFactorsInFactorial(c, 2); | |
if (numOf2Factors >= 12) { | |
if (a == b || b == c) | |
answer += 3; | |
else | |
answer += 6; | |
} | |
} | |
} | |
} | |
return answer; | |
} | |
/** | |
* @return number of factors of given prime In factorial of n | |
*/ | |
private int numOfPFactorsInFactorial(int n, int prime) { | |
if (prime == 2 && numOf2FactorsInFactorial[n] > 0) { | |
return numOf2FactorsInFactorial[n]; | |
} else if (prime == 5 && numOf5FactorsInFactorial[n] > 0) { | |
return numOf5FactorsInFactorial[n]; | |
} | |
int numOfFactors = 0; | |
int multiple = 1; | |
while (n >= multiple) { | |
multiple *= prime; | |
numOfFactors += n / multiple; | |
} | |
if (prime == 2) | |
numOf2FactorsInFactorial[n] = numOfFactors; | |
else if (prime == 5) | |
numOf5FactorsInFactorial[n] = numOfFactors; | |
return numOfFactors; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment