Created
January 26, 2012 02:24
-
-
Save andrew-smith/1680557 to your computer and use it in GitHub Desktop.
Brute-forcing Euler problem 12
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.math.BigInteger; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
public class TriNum { | |
private static final BigInteger TWO = BigInteger.valueOf(2); | |
private static void log(String msg) | |
{ | |
//Logger.getLogger(TriNum.class.getName()).log(Level.INFO, msg); | |
System.out.println(msg); | |
} | |
public static void main(String[] args) { | |
new TriNum().start(); | |
} | |
private static ArrayList<Integer> allSuccess = new ArrayList<Integer>(); | |
//sets the final number that was found | |
public static synchronized void setFinished(int number, int totalFactors) | |
{ | |
found = true; | |
log("" + number + " total factors: " + totalFactors); | |
allSuccess.add(number); | |
//log("####################"); | |
//log("FOUND FACTOR OVER 500"); | |
Logger.getLogger(TriNum.class.getName()).log(Level.INFO, "ANSWER: {0}", Collections.min(allSuccess)); | |
} | |
private static boolean found = false; | |
private void start() | |
{ | |
int currentTriangleNum = 1; | |
int currentNum = 2; | |
while(!found) | |
{ | |
new Thread(new Solver(currentTriangleNum)).start(); | |
currentTriangleNum += currentNum; | |
currentNum++; | |
} | |
} | |
private class Solver implements Runnable | |
{ | |
int number; | |
public Solver(int number) | |
{ | |
this.number = number; | |
} | |
@Override | |
public void run() | |
{ | |
int totalFactors = 1; | |
int b = number / 2; | |
while(b > 0) | |
{ | |
if(number % b == 0) | |
{ | |
++totalFactors; | |
} | |
--b; | |
} | |
if(totalFactors >500) | |
setFinished(number, totalFactors); | |
} | |
} | |
} | |
Running time with threads: 4 minutes 24 seconds.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running time: 4 hours 18 minutes.