Skip to content

Instantly share code, notes, and snippets.

@mellorjc
Created January 3, 2017 17:52
Show Gist options
  • Save mellorjc/07cbff70cea712a48c1e1cc2280327a5 to your computer and use it in GitHub Desktop.
Save mellorjc/07cbff70cea712a48c1e1cc2280327a5 to your computer and use it in GitHub Desktop.
Project Euler problem 12
<!DOCTYPE HTML>
<html>
<body>
<p>Problem 12</p>
<script>
function is_prime(n) {
/*
* Try to divide n by all the numbers from 2 to the square root
* of n. If any divide exactly then we know that n is not prime
* and return false, otherwise if after testing all the mentioned
* numbers then we know that n is prime as so return true.
*/
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
function next_prime(n) {
/*
* Starting from n, as given by the function argument,
* find the next prime by increasing n until n is prime.
* We test if n is prime using the is_prime function.
*/
while (true) {
n = n + 1;
if (is_prime(n)) {
return n;
}
}
}
function prime_factors(n) {
/*
* Starting from 2 (the 1st prime number) as the current prime p, repeatedly
* divide n by p up until there is a remainer, at which point alter the current
* prime p to the next largest prime (using the function next_prime) and repeat
* this procedure until n is 1. Each time p will divide into n, increase the number
* of times p is a prime factor that is recorded in the dictionary pfacs.
*/
var p = 2;
var pfacs = {};
while (n > 1) {
while (n % p == 0) {
n = n / p;
if (!(p in pfacs)) {
pfacs[p] = 0;
}
pfacs[p] = pfacs[p] + 1;
}
p = next_prime(p);
}
return pfacs;
}
function num_factors(pfacs) {
/*
* Given a dictionary, where the keys are the unique prime factors
* and the values are the number of times the unique prime factor
* occurs, we use the form (v_1 + 1)(v_2 + 1)(v_3 + 1)...
* to calculate the number of factors (including non-prime)
*
* Here v_1 is value associated with the 1st key in the dictionary,
* and so number of times that the unique prime factor appears as a
* prime factor.
*/
var r = 1;
for (p in pfacs) {
r = r*(pfacs[p] + 1);
}
return r;
}
/* This is the main loop for solving the problem.
* The program starts at the 1st triangle number.
* It calculates the number of factors this number has.
* It checks if the number of factors is 500 or above.
* If it does, it stops and displays the current triangle number.
* If it doesn't, it goes to the next triangle number and repeats the process.
* It does this until it finds the corrent answer.
*/
var i = 1;
while (true) {
var x = i*(i+1)/2; /* x not contains the ith triangle number */
var num_f = num_factors(prime_factors(x)); /* calculate the number of factors for the ith triangle number */
if (num_f >= 500) { /* if it contains 500 factors of over then stop searching a display the answer */
alert(x);
break;
}
i = i + 1;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment