When trying out the code below as a solution for the Euler Project problem 5. The problem is find the smallest number equally divisible by all numbers from 1 to 20. Every time it is run it presents "Unresponsive Script" window and I need to physically stop the script from running. It seems like something is causing it to hang but I can't quite figure out what. The alert window seems to point to an error with the line the while() starts on but I can't see anything wrong with it.If it looks like it should work I'd appreciate anyone trying it on their machine to see if it works. That way I can eliminate it as a local problem. All suggestions welcome.
var divisible = false;
var n = 2520; // first number divisible by all numbers 1-10
while(divisible === false){ // something wrong here??
n += 2520;
for(var i = 11; i < n; i++) {
if(i % n !== 0){
break;
}
if(i === 20) {
divisible === true;
}
}
}
if(divisible === true){
return console.log("Answer: " +i);
}
Because you break out of your for loop if i % n isn't 0 the very first time. And you never set divisible to true - divisible === true isn't the same as divisible = true
There are several errors in the original code, some pointed out in the answer above. To make it work several fixes are needed.
First, the boolean divisible must be correctly set to true using the assignment operator = inside the for loop instead of === which is used only to check if two values are strictly of the same type AND value.
The next problem is the conditional part of the for loop i < n should be i < 20 because the loop is checking if numbers between 11 and 20 divide evenly into n.The last fix to make the code run correctly is the order of the condition if the first if statement which should read if(n % i !== 0) and not if(i % n !== 0). I think it might be this specific part that caused the code to crash and generate the "Unresponsive Script" alert in the browser.
Here is the fixed code.
var divisible = false;
var n = 2520; // smallest number divisible by all numbers 1-10
while(divisible === false){
n += 2520; // increment n on each new pass
// loop numbers between 11 and 20
for(var i = 11; i <= 20; i++) {
if(n % i !== 0){ // check if i divides equally into n
// if not break out of current loop and start again
break;
}
// if i reaches 20 then all the numbers divided equally into n
if(i === 20) {
// set value of divisible to true to cancel while loop
divisible = true;
}
}
}
// return the last value of n
return console.log("Answer: " +n);
Related
So,
I'm starting to learn how to code and now I have only one problem.
My code is functioning very well, until he says that the numbers 1 and 0 are prime.
I already tried to add them to exception, change the calculation and still printing that is prime.
Here's the code:
function testPrimeNumber(num)
{
Number(num)
for (var i = 2; i < num; i++)
{
if (num % i == 0)
{
return ("The number "+num+" isn't prime.");
}
else {}
}
return ("The number "+num+" is prime.");
}
console.log("result for 1:", testPrimeNumber(1));
What am I doing wrong here?
You should test for 0 and 1 at the start of the function. At the moment your code is skipping the for loop (because 1 < 2 and 0 < 2) and going straight to saying the number is prime.
The problem is: Print out how much odd numbers there are in a given number.
function oddCount(n) {
var odd = [];
for (i = 0; i < n; i++) {
if (i % 2 == 1) {
odd.push([i]);
}
}
return odd.length;
}
console.log(oddCount(8));
As we can see, it works properly, however, on codewars, it wants me to optimize it to run faster. Can someone show me how so I can learn it quickly please.
function oddCount(n) {
var odd = [];
for (i = 0; i < n; i++) {
if (i & 0x1 == 1) {
odd.push([i]);
}
}
return odd.length;
}
console.log(oddCount(8));
or
function oddCount(n) {
return (n - (n & 0x01)) / 2;
}
console.log(oddCount(8));
Neither "ceil" or "floor" is a correct answer as a one liner. "ceil" will make the division Base 1, "floor" will make the division Base 0. So both could be used in an implementation, but the "polarity" of n matters.
It's necessary to check whether the input number is odd or even.
function oddCount(n) {
// odd / even check
if (n % 2 == 0) {
// its even, we can divide by 2
return n / 2
}
else {
// n is odd, so we must include n as a count+1 itself
return ((n - 1) / 2) + 1
}
}
// Disclaimer: Are negative numbers odd or even? In this code they
// apparently aren't handled. So the set of numbers are integers from
// 0 to +Infinity
// Test cases:
console.log( oddCount(8) ); // 4
console.log( oddCount(9) ); // 5
But this code "breaks" if n itself is 0 or less. So we need to fix it:
Right after we say function oddCount(n) {, put:
if (n < 1) return 0;
All worries solved. But still debate on whether 0 is odd or even, and whether -1 is odd and -2 is even.
I believe this should work.
function oddCount(n) {
return Math.ceil(n/2);
}
console.log(oddCount(8));
If the number is an even number, there's n/2 odd numbers
Eg if n is 6
*1*,2,*3*,4,*5*,6
If it is an odd number, there's n/2+1 odd numbers. Because n-1 would be even
Eg if n is 5
*1*,2,*3*,4, + *5*
So basically
if (n%2==0) return n/2
else return (n-1)/2+1
The for loops aren't needed
Also like the others pointed out, ceiling is a more concise way to do it
return Math.ceil(n/2)
I have a function for Project Euler #7. Towards the end, I changed the code from primeArray.push(i); to primeArray.unshift(i) and return primeArray[primeArray.length - 1]; to return primeArray[0];. This altered the return. In the former. It returned the correct answer, 104021, while the latter returned 20001, which is not even prime. I do not understand why that is.
function primeFinder(primeTarget) {
//since 2 is the only even prime, putting it here saves us some effort in checking primality by just iterating over the odd numbers
//it also helps the for loop since we are only interested in checking for divisors among previous primes.
let primeArray = [2];
let i = 3;
while (primeArray.length < primeTarget) {
let primeLogger = false;
//We don't need to check for divisibility by 2, so j can equal 1
for (j = 1; j < primeArray.length && primeArray[j] < Math.sqrt(i); j++) {
if (i % primeArray[j] === 0) {
primeLogger = true;
//Since we have found a divisor and changed primeLogger, we can exit the loop
break;
}
}
//Where the break goes to, and also where the for loop goes to once finishes
if (primeLogger === false) {
primeArray.push(i);
}
i += 2;
}
return primeArray[primeArray.length - 1];
}
console.log(primeFinder(10001));
Because primeArray is now in descending order but your loop still searches from start to end; now from biggest towards smaller values. Until it finds something that is >= Math.sqrt(i) which most likely will be the very first check, j=1.
Then it ends the loop with primeLogger === false
so for example, for:
i=9, j=1
primeArray === [7,5,3,2]
primeArray[j] === 5
And since the check 5 < Math.sqrt(9) is false the loop is finished.
Therefore 9 is a prime number and is now added to the start of primeArray.
this is only a part of the code
What does this loop do? This is a JavaScript for loop I'm trying to learn some JavaScript with modulo in it but I can't understand this one.
for (var x = 2; x < n; x++) {
if (n % x === 0) {
return false;
}
}
return true;
}
}
The above code will increment x (starting at 2) until it's 1 less than n. Each iteration, it checks if "n" can be evenly divided by "x". (Modulos are used to find the remainder). If it is evenly divisible, the program return false.
This code is a prime number checker. If it gets to the bottom it means "n" can only be divided by itself and returns true.
I'm working on a program designed to generate prime numbers, and I'm trying to find the 10001st prime number. Each time the loop runs, it tests variable i to see if it's divisible by variable j, which is part of another loop that goes up to half of i. If i is divisible by j then it adds one to variable prime, and when the loop's done it checks to see if variable prime is larger than two; if it is, then i is not prime. If it is prime, it gets push()ed to the variable array, which stores all the primes. Sorry if that's a little confusing.
My problem is that although this code works, whenever I set the first for loop too high (here I have it end at 100000), my browser freezes:
var prime = 0;
var array = [];
for(var i = 2; i <= 100000; i+=1) {
var prime = 0;
for(var j = 0; j <= i/2; j+=1) {
if(i % j === 0) {
prime += 1;
}
}
if(prime < 2) {
array.push(i);
}
}
console.log(array.length)
I know I could just copy and paste all the prime numbers but I want to make the program work. Any ideas to make the program stop freezing?
This is because the time complexity of your algorithm is pretty much O(n^2). Sieve of Eratosthenes created a better algorithm that will prevent your browser from freezing.
Here is one way of doing it:
var exceptions = {
2: 2,
3: 3,
5: 5,
7: 7
}
var primeSieve = function (start, end) {
var result = [];
for (start; start < end; start++) {
if (start in exceptions) result.push(start);
if (start > 1 && start % 2 !== 0 && start % 3 !== 0 && start % 5 !== 0 && start % 7 !== 0) {
result.push(start);
}
}
return result;
};
You can obviously make this look prettier, but I just did it quickly so you can get the point. I hope this helps! Let me know if you have further questions.