Euler 7 Javascript - javascript

Can someone help with this code? It's supposed to get the 10,001th prime number. I know the is_prime function works to test if a number is prime since I successfully utilized this code for a previous problem. Now I'm just trying to call that in a for loop until counter hits what I want, while storing the most recent number into a variable 'holder' and printing holder at the end.
function is_prime(num) {
if (isNaN(num)) return false;
for (var i=2; i<=Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
function getBigPrime () {
var holder = 0;
var counter = 0;
for (var k=3; counter<=10000; k+=2) {
if (is_prime(k))
holder = k;
counter += 1;
}
console.log(holder);
}
getBigPrime();

If you omit the brackets for an if block, only the first line will actually be part of your block. Your current if statement behaves like this:
if (is_prime(k)) {
holder = k;
}
counter += 1;
Also, your loop skips 2, the first prime number.

You have a scoping error with counter.
For your for loop you can initialize counter = 1; to account for 2 and leave as is
http://jsfiddle.net/XtTYm/2/
function is_prime(num) {
if (isNaN(num)) return false;
var sq = Math.sqrt(num);
for (var i=2; i<=sq; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
function getBigPrime () {
var holder = 0;
var counter = 1;
for (var k=3; counter<=10000; k+=2) {
if (is_prime(k)){
holder = k;
counter += 1; // should be inside the if
}
}
console.log(holder);
}
getBigPrime();

Related

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>

find the next palindrome using loop

i want to find next smallest palindrome but im not allowed to use some built-in function. so i create this code :
function reverse(nums) {
var reverse = "";
for (var i = String(nums).length - 1; i >= 0; i--) {
reverse += String(nums)[i];
}
return reverse;
}
function Palindrome(num) {
if (String(num).length < 2) {
return num + 1
}
for (var i = num + 1; i < num + 3; i++) {
if (String(i) === reverse(num)) {
return i
}
}
}
console.log(Palindrome(23)) // 32
first function will reverse the string and the second will find the nearest palindrome.
on the test case, the result are supposed to be 33.
but when i run the code the result is :
console.log(Palindrome(23))// 32
it only reversing the numbers.
could you help me to find what could be wrong from my code?
thanks before.
correct code is:
function reverse(nums) {
var reverse = "";
for (var i = String(nums).length - 1; i >= 0; i--) {
reverse += String(nums)[i];
}
return reverse;
}
function Palindrome(num) {
if (String(num).length < 2) {
return num + 1
}
for (var i = num + 1; ; i++) {
if (String(i) === reverse(i)) {
return i
}
}
}
console.log(Palindrome(23))
you were doing reverse of num in place of i
The check should be for reverse of i, not reverse of num. Try the following condition.
if (String(i) === reverse(i)) { ... }
you don't need to reverse, as it would take O(n), if you iterate and check only for half the length of num, you can improve performance.
Here I'm matching the digits of number at places from beginning and the end.
So, the first digit should match the last, second should match the second last and so on. I any such match fails the number is not palindrome.
And this, way you only have to go upto half the length of number (after converting it to string);
function Palindrome(num) {
num = "" + num;
for(var i = 0; i < num.length/2; i++)
{
if(num[i] != num[num.length - (i+1)])
return false;
}
return true;
}
function nextPalindrome(num)
{
while(!Palindrome(++num)){}
return num;
}
console.log(nextPalindrome(22));
console.log(nextPalindrome(23));
console.log(nextPalindrome(232));
console.log(nextPalindrome(122));
console.log(nextPalindrome(1001));
I have used while loop here. You can try this:
function reverse(nums) {
var reverse = "";
for (var i = String(nums).length - 1; i >= 0; i--) {
reverse += String(nums)[i];
}
return reverse;
}
function Palindrome(num) {
if (String(num).length < 2) {
return num + 1;
}
var i=num;
while(i!=0) {
if (String(i++) === reverse(num)) {
return --i;
}
num=i;
}
}
console.log(Palindrome(23));

Why is this function creating an infinite looop?

The first function determines if a number is prime. The second function is supposed to create an array with all prime numbers up to and including the max value, but it gives me an infinite loop for some reason.
function isPrime(num) {
for (i = 2; i < num; i++) {
if (num % i === 0) {
return false
}
}
if (num <= 1) {
return false;
}
return true;
}
function primes(max) {
var all = [];
for (i = 2; i <= max; i++) {
if (isPrime(i)) {
all.push(i);
}
}
}
primes(17);
Your i variable is global, so both functions use the same i. This means the first function changes it while the second one is looping.
As the first function will have set i to num-1 when it finishes, and num was the value of i before executing it, it effectively decrements i with one. And so i will get the same value in the next iteration of the loop in the second function, never getting forward.
Solve this by putting the var keyword in both functions.
for(var i=2; // ...etc)
The variable i in your two loops are global variables and they overwrite each other so the first loop never ends.
In ur code problem is with the scope of variable i, In prime no calculation, u can check upto the sqrt of no, if no is not divisible by any no upto its sqrt, then it will a prime no, Try this:
function isPrime(num) {
let k = Math.sqrt(num);
for (let i = 2; i <= k; i++) {
if (num % i === 0) {
return false
}
}
return true;
}
function primes(max) {
let all = [];
for (let i = 2; i <= max; i++) {
if (isPrime(i)) {
all.push(i);
}
}
console.log(all)
}
primes(17);
primes(25);

Javascript code to find prime numbers doesn't work

I run this function, which i triggered with a button, and it should be printing the prime numbers. Instead, it printed all the numbers that it checked. The user is supposed to enter a number(for example 100) and all the numbers lower than it will be checked if they are prime, and if they are, they will be printed.(i is the number that is being checked)
function findeprime(num) {
for (i = 2; i < num; i++) {
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) continue;
}
document.write(i + " is prime <br/>");
}
}
What am i doing wrong???
Your continue is only breaking out of the inner loop. I'd recommend something like this
function findeprime(num) {
var isPrime;
for (var i = 2; i < num; i++) {
isPrime = true;
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) isPrime = false;
}
if (isPrime) document.write(i + " is prime <br/>");
}
}
It seems like your continue statement is misplaced. It is affecting the inner loop while your code will work properly only if it affected the outer loop.
Since you can't have a continue statement affect an outer loop/block, try the following:
function findeprime(num) {
for (i = 2; i < num; i++) {
var prime = true;
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) {
prime = false;
break;
}
}
if(prime) alert(i + " is prime");
}
}
findeprime(14);
As already pointed out, your continue is breaking the script out of the wrong loop. You can alternatively label the loop you want to break out of:
function findeprime(num) {
checknum: for (i = 2; i < num; i++) {
for (coun = 2; coun < i; coun++) {
if(i % coun == 0) continue checknum;
}
document.write(i + " is prime <br/>");
}
}
findeprime(20);
Apparently everyone already gave you the answer, however i´m gonna post an additional example, for knowledge purposes.
Number.prototype.isPrime = function() {
for (var i = 2; i < this; i++) {
if (this % i == 0) {
return false;
}
}
return true;
};
function findPrimes(num) {
var results = [];
for (var i = 2; i <= num; i++) {
if (i.isPrime()) results.push(i);
}
return results;
}
var primes = findPrimes(1000);
document.write(primes.join(', '));

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));

Categories