Browse Source

fix highly factorable triangular number search to run faster

master
Charles Reid 8 years ago
parent
commit
9203d84f8e
  1. 20
      java/Problem012.java
  2. 20
      scratch/012/Triangular.java

20
java/Problem012.java

@ -4,6 +4,10 @@ @@ -4,6 +4,10 @@
* This program finds the first triangular number with over 500 divisors.
*/
public class Problem012 implements EulerSolution {
public static void main(String[] args) {
Problem012 p = new Problem012();
System.out.println(p.run());
}
public String run() {
return new Long( findTriangularNumber(500) ).toString();
@ -11,11 +15,23 @@ public class Problem012 implements EulerSolution { @@ -11,11 +15,23 @@ public class Problem012 implements EulerSolution {
/** Find a triangular number with over k divisors. */
public static long findTriangularNumber(long k) {
long n = 1;
int divisors = 0;
// We want first divisor with OVER k divisors
// Note: the smallest number with 500 factors
// has approx log_2( 500 ) prime factors.
// That's 8.9, or rounding down, 8.
// A number with 2^9 prime divisors has 512 factors.
//
// Next, we know the value of n is proportional to the
// square root of the expression, so we approximate
// our starting point by picking a number
// that will start at or below the right neighborhood
// and work our way up.
//
long n = (long)(Math.sqrt(2*3*5*7*11*13*17*19));
long tri = 0;
// We want first number with OVER k divisors
while(divisors <= k) {
n++;
tri = EulerLib.triangleLong(n);

20
scratch/012/Triangular.java

@ -12,17 +12,19 @@ public class Triangular { @@ -12,17 +12,19 @@ public class Triangular {
public static void findTriangularNumber(long k) {
int divisors = 0;
// Note: the smallest a number with 500 divisors could
// possibly be (strictly speaking, min would be larger, but
// estimate is)
// Note: the smallest number with 500 factors
// has approx log_2( 500 ) prime factors.
// That's 8.9, or rounding down, 8.
// A number with 2^9 prime divisors has 512 factors.
//
// log_2( 500 )
//
// which is ~8.9
//
// Start search at 2^9 to speed things up.
// Next, we know the value of n is proportional to the
// square root of the expression, so we approximate
// our starting point by picking a number
// that will start at or below the right neighborhood
// and work our way up.
//
long n = (long)(Math.sqrt(2*3*5*7*11*13*17*19));
long n = (long)(Math.pow(2,9));
// We want first number with OVER k divisors
while(divisors <= k) {

Loading…
Cancel
Save