How to optimize the project euler #10 problem for FCC environment? - javascript

// the following code is generating accurate answer in my editor, but I want to optimize the code to pass the tests in freecodecamp environment. Can anybody shed the light upon this problem?
function isPrime(param) {
if (param == 2) {
return true;
}
if (param % 2 == 0) {
return false;
}
var max = Math.ceil(Math.sqrt(param));
for (var i = 3; i <= max; i += 2) {
if (param % i == 0) {
return false;
}
}
return true;
}
function primeSummation(n) {
var primeArr = [];
for (var i = 2; i < n; i++) {
if (isPrime(i)) {
primeArr.push(i);
}
}
var sumArray = primeArr.reduce(function add(a, b) {
return a + b;
}, 0);
console.log(sumArray)
return sumArray;
}
primeSummation(2000000);

When you have a long range of natural numbers (1...n) to check for them being prime, then it is not efficient to test them individually like you do with isPrime. It will be more efficient to perform the sieve of Eratosthenes over that range and then calculate the sum from the resulting array.

Related

Memoization giving less performance and taking more time

I was solving project euler in freecodecamp. When solving problem no 14 i use recursion and tried to increase the performance using memorization. But without memoization it is taking less time to execute and with memoization it is taking more time. Is memoization implementation is correct? What is wrong with this code? Can any one explain?
//Memoized version of the longestCollatzSequence project euler
let t1 = Date.now();
// function recurseWrapper(n) {
// let count = 0;
// let memo = {}
// function recurseCollatzSequence(n) {
// if (n in memo) {
// return memo[n];
// } else {
// if (n === 1) {
// return;
// } else if (n % 2 === 0) {
// count++;
// memo[n / 2] = recurseCollatzSequence((n / 2))
// } else {
// count++;
// memo[(3 * n) + 1] = recurseCollatzSequence(((3 * n) + 1))
// }
// return count
// }
// }
// return recurseCollatzSequence(n);
// }
//Without memoization (better performance)
function recurseWrapper(n) {
let count = 0;
function recurseCollatzSequence(n) {
if (n === 1) {
return;
} else if (n % 2 === 0) {
count++;
recurseCollatzSequence((n / 2))
} else {
count++;
recurseCollatzSequence(((3 * n) + 1))
}
return count
}
return recurseCollatzSequence(n);
}
function longestCollatzSequence(n) {
let max = 0;
let startNum = 0;
for (let i = n; i > 1; i--) {
let changeMax = recurseWrapper(i)
if (changeMax > max) {
max = changeMax;
startNum = i;
}
}
return startNum;
}
console.log(longestCollatzSequence(54512))
let t2 = Date.now() - t1;
console.log(`time taken by first instruction ${t2}`);
console.log(longestCollatzSequence(900000));
let t3 = Date.now() - t1 - t2
console.log(`time taken by second instruction ${t3}`);
let t4 = Date.now() - t1 - t2 - t3
console.log(longestCollatzSequence(1000000))
console.log(`time taken by third instruction ${t4}`);
From my limited understanding of the collatz conjecture, when starting at a number n, with all of the operations that you do, you should never see the same number again until you reach 1 (otherwise you would end up in an infinite loop). So your memo object will always hold unique keys that will never match the current number n, so if (n in memo) will never be true.
It actually seems that you want to memoize your results for further calls recurseWrapper() within your loop, so that you can prevent computing results you've already seen. At the moment you are not doing that, as you are creating a new memo object each time you call recurseWrapper(), removing all of the memoized values. You can instead return your inner auxiliary recursive wrapper function that closes over the memo object so that you keep the one memo object for all calls of the recursive wrapper function.
But even then we will still face issues, because of how the count is being calculated. For example, if you call recurseWrapper(n) and it takes 10 iterations to call recurseCollatzSequence(k), the returned count of recurseCollatzSequence(k) is going to be 10 plus whatever number it takes to compute the Collatz sequence for k. If we memoize this number, we can face issues. If we again call recurseWrapper on another number m, recurseWrapper(m), and this time it takes 20 iterations to get to the same call of recurseCollatzSequence(k), we will use our memoized value for k. But this value holds an additional count for the 10 that it took to get from n to k, and not just the count that it took to get from k to 1. As a result, we need to change how you're computing count in your recursive function so that it is pure, so that calling a function with the same arguments always produces the same result.
As Vincent also points out in a comment, you should be memoizing the current number, ie: memo[n] and not the number you're about to compute the Collatz count for (that memoization is done when you recurse):
function createCollatzCounter() {
const memo = {};
return function recurseCollatzSequence(n) {
if (n in memo) {
return memo[n];
} else {
if (n === 1) {
memo[n] = 0;
} else if (n % 2 === 0) {
memo[n] = 1 + recurseCollatzSequence(n / 2);
} else {
memo[n] = 1 + recurseCollatzSequence((3 * n) + 1);
}
return memo[n];
}
}
}
function longestCollatzSequence(n) {
let max = 0;
let startNum = 0;
const recurseWrapper = createCollatzCounter();
for (let i = n; i > 1; i--) {
let changeMax = recurseWrapper(i)
if (changeMax > max) {
max = changeMax;
startNum = i;
}
}
return startNum;
}
console.time("First");
console.log(longestCollatzSequence(54512));
console.timeEnd("First");
console.time("Second");
console.log(longestCollatzSequence(900000));
console.timeEnd("Second");
console.time("Third");
console.log(longestCollatzSequence(1000000));
console.timeEnd("Third");
In comparison, the below shows times without memo:
//Without memoization (better performance)
function recurseWrapper(n) {
let count = 0;
function recurseCollatzSequence(n) {
if (n === 1) {
return;
} else if (n % 2 === 0) {
count++;
recurseCollatzSequence((n / 2))
} else {
count++;
recurseCollatzSequence(((3 * n) + 1))
}
return count
}
return recurseCollatzSequence(n);
}
function longestCollatzSequence(n) {
let max = 0;
let startNum = 0;
for (let i = n; i > 1; i--) {
let changeMax = recurseWrapper(i)
if (changeMax > max) {
max = changeMax;
startNum = i;
}
}
return startNum;
}
console.time("First");
console.log(longestCollatzSequence(54512))
console.timeEnd("First");
console.time("Second");
console.log(longestCollatzSequence(900000));
console.timeEnd("Second");
console.time("Third");
console.log(longestCollatzSequence(1000000));
console.timeEnd("Third");
Here is a streamlined version of the solution with minimal noise around memoization and recursion.
let memo = {};
function collatzSequence(n) {
if (! (n in memo)) {
if (n == 1) {
memo[n] = 1;
}
else if ((n % 2) === 0) {
memo[n] = 1 + collatzSequence(n/2);
} else {
memo[n] = 1 + collatzSequence(3*n + 1);
}
}
return memo[n];
}
function longestCollatzSequence(n) {
let max = 0;
let startNum = 0;
for (let i = n; i > 1; i--) {
let changeMax = collatzSequence(i)
if (changeMax > max) {
max = changeMax;
startNum = i;
}
}
return startNum;
}
console.log(longestCollatzSequence(14))
And if you're willing to accept a bit of golf, here is a shorter version still of the first function.
let memo = {1: 1};
function collatzSequence(n) {
if (!(n in memo)) {
memo[n] = 1 + collatzSequence(0 === n%2 ? n/2 : 3*n+1);
}
return memo[n];
}
The reason why this matters has to do with how we think. As long as code reads naturally to us, how long it takes to write and think about it is directly correlated with how long it is. (This has been found to be true across a variety of languages in many places. I know that Software Estimation: Demystifying the Black Art certainly has it.) Therefore learning to think more efficiently about code will make it faster for you to write.
And that is why learning how to use techniques without talking about the technique you're using makes you better at that technique.
After spending some time figuring out I found a working solution.
The code below improved time complexity. Thanks all for helping me.
//Memoized version of the longestCollatzSequence project euler
let memo = {}
function recurseWrapper(n) {
let count = 0;
if (n in memo) {
return memo[n];
} else {
function recurseCollatzSequence(n) {
if (n === 1) {
return;
} else if (n % 2 === 0) {
count++;
recurseCollatzSequence((n / 2))
} else {
count++;
recurseCollatzSequence(((3 * n) + 1))
}
return count
}
let c = recurseCollatzSequence(n);
memo[n] = c;
return c;
}
}
function longestCollatzSequence(n) {
let max = 0;
let startNum = 0;
for (let i = n; i > 1; i--) {
let changeMax = recurseWrapper(i)
if (changeMax > max) {
max = changeMax;
startNum = i;
}
}
return startNum;
}
longestCollatzSequence(14)

Using forEach Loop Generating prime number in Javascript between 1 to 50 [duplicate]

This question already has answers here:
Check Number prime in JavaScript
(47 answers)
Closed 2 years ago.
Here's my code but my answer is not that which i want..
Please Check This and give me a solution to get prime number using Foreach Loop b/w 1-50
Thanks In Advance :)
function isPrime(num) {
for ( var i = 2; i < num; i++ ) {
if ( num % i === 0 ) {
return false;
}
}
return true;
}
var txt = "";
function shown(n) {
var arr = [2];
arr.forEach(myFunction);
document.getElementById("foreach").innerHTML = txt;
// document.getElementById('forLoop').innerHTML = arr; // use arr result on your own
}
function myFunction(arr, index, array) {
var i;
var arr = [2];
if ( isPrime(i) ) {
arr.push(i);
}
txt += arr + "<br>";
}
shown(50);
This is probably a too-advanced answer for a homework of this level, but technically it follows the rules (use Array.forEach) and it works.
The primes() generates new primes based on previous primes. So it won't test the reminder of all integers, thus more effecient. There are several arrow function uses, too, to keep things short. If you indeed use this answer, please try to read the relevant documentations and learn:
Iterators and Generators
Arrow function expressions
for...of
Template literals
Seriously, try to think step-by-step. That's how you learn anything.
function* primes() {
const previous = [];
for (let i = 2; true; i++) {
let isPrime = true;
for (let p of previous) {
if (i % p === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
previous.push(i);
yield i;
}
}
}
function* takeUntil(cb, iter) {
for (let val of iter) {
if (cb(val)) {
return;
}
yield val;
}
}
function showArrayIn(arr, container) {
arr.forEach(p => container.innerHTML += `${p},<br/>`); // technically, we used Array.forEach.
}
showArrayIn(
// get the prime number array declarativly
Array.from(takeUntil(n => n >= 50, primes())),
// show in the container specified
document.getElementById("results")
);
Primes:
<div id="results"></div>
function primeFactorsTo(max)
{
var store = [], i, j, primes = [];
for (i = 2; i <= max; ++i)
{
if (!store [i])
{
primes.push(i);
for (j = i << 1; j <= max; j += i)
{
store[j] = true;
}
}
}
return primes;
}
console.log(primeFactorsTo(5));
console.log(primeFactorsTo(15));
I Think so this is the correct answer which i deserve..
It is code lover short and aggressive
function primes(limit)
{
var prime=[], i=1;
while (++i < limit+1) prime.reduce((a,c)=>(i%c)*a,1) && prime.push(i);
prime.unshift(2);
return prime;
}
[50].forEach(n=>document.getElementById('foreach').innerHTML=(`${primes(n)}`));
Consider the following example.
function isPrime(num) {
if (num === 1) {
return false;
} else if (num === 2) {
return true;
} else {
for (var x = 2; x < num; x++) {
if (num % x === 0) {
return false;
}
}
return true;
}
}
function shown(n) {
var list = [];
for (var i = 1; i <= n; i++) {
list.push(i);
}
list.slice().reverse().forEach(function(n, k, o) {
if (!isPrime(n)) {
list.splice(o.length - 1 - k, 1);
}
});
document.getElementById("show").innerHTML = list;
}
shown(50);
Prime: <p id="show"></p>

Prime Factor Calculator JS - Can't find infinite loop

So I was trying to go back over my problem solving abilities and wanted to redo my prime factor calculator. Code refactoring, more efficient, etc as I was a beginner at JS when I made it.
In recreating it I have come across a rather large issue - an infinite loop. Now, I've broken down my function into different parts and called them separately - they work fine. The main function itself even works fine, so long as the number is 10 or less. But for some reason whenever I call the function with a parameter greater than 10 there is an infinite loop.
I'm sorry if the answer is glaringly obvious, it's quite late at night. I just can't seem to spot it.
The plain code is here:
var findPrimeFactors = function (number) {
var isPrime = function (number) {
var primes = [];
for (i = 2; i < number; i++) {
if (number % i === 0) {
return false;
}
}
primes.push(number);
return primes;
};
var findFactors = function (number) {
var factors = [];
for (i = 2; i < number; i++) {
if (number % i === 0) {
factors.push(i);
}
}
return factors;
};
var factors = findFactors(number);
var primes = [];
for (i = 0; i < factors.length; i++) {
primes += isPrime(factors[i]);
}
return primes;
};
console.log(findPrimeFactors(10));
The fiddle for the code is here: https://jsfiddle.net/uk26q4ff/
Thanks everyone!
Likely you are hitting this because in each function you aren't declaring i so it is using it from the global scope.
I found a couple of bugs.
Your isPrime function should return either true or false, not an array
the loop in findFactors should include the 'number' value (changed < to <=)
The infinite loops was cause by using the same variable i in every
loop.
Finally I changed the following I changed the following line
at the end: if (isPrime(factors[k])) primes.push(factors[k]);
Here is how I would do it:
var findPrimeFactors = function (number) {
var isPrime = function (number) {
var primes = [];
for (i = 2; i < number; i++) {
if (number % i === 0) {
return false;
}
}
//primes.push(number);
//return primes;
return true;
};
var findFactors = function (number) {
var factors = [];
for (j = 2; j <= number; j++) {
if (number % j === 0) {
factors.push(j);
}
}
return factors;
};
var factors = findFactors(number);
var primes = [];
for (k = 0; k < factors.length; k++) {
//primes += isPrime(factors[k]);
if (isPrime(factors[k])) primes.push(factors[k]);
}
return primes;
};
console.log(findPrimeFactors(37));

Project Euler Q3 JavaScript

My code is as follows:
function is_prime(num) {
for(i=2; i < num; i++) {
if(num % i === 0) {
return false;
} else {
return true;
}
}
};
var total = 600851475143,
b = 2,
storemax = 0;
function max_prime(total) {
if(total % b === 0) {
storemax = total / b;
if (is_prime(storemax) = true) {
console.log(storemax);
} else {
b += 1;
max_prime(total);
}
}
};
What am I doing wrong? I've been stuck on this for a while... trying to do the odin project web programming course.
The problem is found in your max_prime function
if (is_prime(storemax) = true) {
Here you are using an assignment operator when you should be using a comparison operator
Change this to
if (is_prime(storemax === true) {
This will check if the value of is_prime(storemax) is equal to true.
Also, JavaScript functions follow a lowerCamelCase convention. Change is_prime to isPrime and max_prime to maxPrime

Generating random number in Array without repeatition - JavaScript

so I know this questing has been asked, but all the answers that were given are already known to me. I don't want to make a variable of all the posible numbers (that was always the answer). So to go to the question, I want to make a random number generator, that will generate me 7 numbers, that must not be the same. For example, I get random numbers:
"5,16,12,5,21,37,2" ... But I don't want the number 5 to be used again, so I want different numbers. I made a code for the generation, but I can not think of any good method/way to do this. I was thinking that maybe check if the number is already in array and if it is, then generate another number, but as I'm amateur in JavaScript, I don't know how to do this. So here is my JavaScript code:
// JavaScript Document
function TableOn()
{
document.write("<table border='1'>");
}
function TableOff()
{
document.write("</table>");
}
function RandNum()
{
var n = new Array();
for(var i=0;i<7;i++)
{
n[i] = Math.round((1+(Math.random()*40)));
}
TableOn();
for(var c=0;c<7;c=c+1)
{
document.write("<tr><td>"+n[c]+"</td></tr>");
}
TableOff();
}
In HTML I just have a button, that is onclick="RandNum()" ... Pardon for my English.
I would do it like this:
var nums = [], numsLen = 5, maxNum = 100, num;
while (nums.length < numsLen) {
num = Math.round(Math.random() * maxNum);
if (nums.indexOf(num) === -1) {
nums.push(num);
}
}
This generates an array with 5 random numbers in the range 0..100.
(numsLen cannot be greater than maxNum.)
These commands can be used to check if a value is/is not in your array:
if ( !!~n.indexOf(someVal) ) {
// someVal is in array "n"
}
if ( !~n.indexOf(someVal) ) {
// someVal is not in array "n"
}
I'd use a string, storing the generated random numbers with a divider. Then check if the newly generated number is in that string.
Something like this
generated = "";
for(var i=0;i<7;i++)
{
generate = Math.round((1+(Math.random()*40))); //generate = 5
while (generated.indexOf("[" + generate + "]") != -1) { //checking if the [5] is already in the generated string, and loop until it's a different number
generate = Math.round((1+(Math.random()*40))); //get a new random number
}
generated += "[" + generate + "]";
n[i] = generate;
}
or you can take another longer approach
for(var i=0;i<7;i++)
{
repeated = true;
while (repeated) {
repeated = false;
generate = Math.round((1+(Math.random()*40)));
for (var a=0; a < i, a++) {
if (generate == n[a]) { repeated = true; }
}
}
n[i] = generate;
}
Here's a function to generate an array of n unrepeated random numbers in [min, max):
function rands(n, min, max) {
var range = max - min;
if (range < n)
throw new RangeError("Specified number range smaller than count requested");
function shuffle() {
var deck = [], p, t;
for (var i = 0; i < range; ++i)
deck[i] = i + min;
for (i = range - 1; i > 0; --i) {
p = Math.floor(Math.random() * i);
t = deck[i];
deck[i] = deck[p];
deck[p] = t;
}
return deck.slice(0, n);
}
function find() {
var used = {}, rv = [], r;
while (rv.length < n) {
r = Math.floor(Math.random() * range + min);
if (!used[r]) {
used[r] = true;
rv.push(r);
}
}
return rv;
}
return range < 3 * n ? shuffle() : find();
}
This code checks the range of possible values and compares it to the number of random values requested. If the range is less than three times the number of values requested, the code uses the shuffle to avoid the terrible performance of the lookup approach. If the range is large, however, the lookup approach is used instead.
Not sure if OP's requirement of non-repeating is really needed, but here's a fiddle of something that could work if your number range isn't too big:
http://jsfiddle.net/6rEDV/1/
function range(start, end, step) {
if (typeof step === 'undefined') {
step = 1;
}
if (typeof start === 'undefined' || typeof end === 'undefined') {
throw TypeError('Must have start and end');
}
var ret = [];
for (var i = start; i <= end; i += step) {
ret.push(i);
}
return ret;
};
// source: http://stackoverflow.com/a/6274381/520857
function shuffle(o) { //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
function getNonRepeatingRand(min, max, num) {
var arr = shuffle(range(min, max));
return arr.slice(0, num-1);
}
// Get 7 random numbers between and including 1 and 1000 that will *not* repeat
console.log(getNonRepeatingRand(1,1000,7));
A possibly slower, but less memory intensive method:
http://jsfiddle.net/Qnd8Q/
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getNonRepeatingRand(min, max, num) {
var ret = [];
for (var i = 0; i < num; i++) {
var n = rand(min, max);
if (ret.indexOf(n) == -1) {
ret.push(n);
} else {
i--;
}
}
return ret;
}
console.log(getNonRepeatingRand(1,5,5));
var n = new Array(),num;
function TableOn()
{
document.write("<table border='1'>");
}
function TableOff()
{
document.write("</table>");
}
function check_repition()
{
num=Math.round((1+(Math.random()*40)))
if(n.indexOf(num)==-1)
return true;
else
return false;
}
function RandNum()
{
for(var i=0;i<7;i++)
{
if(check_repition())
n[i] =num;
else // keep checking
{
check_repition()
n[i] =num;
}
}
TableOn();
for(var c=0;c<7;c=c+1)
{
document.write("<tr><td>"+n[c]+"</td></tr>");
}
TableOff();
}
RandNum()

Categories