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(', '));
Related
So what I'm trying to do is use a function that prompts to enter a number and then prints all prime numbers up till that number. I have the code as far as I know but I keep getting an error that the bracket following prime(num) is wrong. Not sure what I'm doing wrong here, would appreciate any help.
function p5Bela() {
var num = prompt("Please enter a number: ", "");
for (i = 2; i <= num; i++) {
if (prime(i)==true) {
alert(i);
}
}
prime(num) {
var flag = true;
var d = 2;
while (flag==true && d <= num/2) {
if (num%d == 0) {
flag = false;
}
d++;
}
return flag;
}
}
Simplest Way
function isPrime(num) {
for(var i = 2; i < num; i++)
if(num % i === 0) return false;
return num > 1;
}
With the ES6 syntax:
const isPrime = num => {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num > 1;
}
You can also decrease the complexity of the algorithm from O(n) to O(sqrt(n)) if you run the loop until square root of a number:
const isPrime = num => {
for(let i = 2, s = Math.sqrt(num); i <= s; i++)
if(num % i === 0) return false;
return num > 1;
}
My function takes an integer array of divisors, a low number and a high number as parameters. It prints the range between a low and a high number.
If the number in the range is divisible by all elements of the array, print "all match".
If at least one number matches, print "one match".
If no number matches, print the number.
But, I can't figure out how to write my if-else statements properly. It only prints the numbers that match. When I change the else-if statement, it prints all the numbers twice.
function allFactors(factors, num){
var nums = [];
for(var i = 0; i < factors.length; i++) {
var factor = factors[i];
if(num % factor === 0){
nums.push(factor);
}
}
if(nums.length === factors.length){
return true;
}
return false;
}
//console.log(allFactors([2,3],6))
function isFactor(num, factor) {
if(num % factor === 0) {
return true;
}
return false;
}
function matches(factors, low, high) {
var skipper = false
for(var i = low; i <= high; i++) {
if(allFactors(factors,i)){
console.log(i + " match_all")
} else {
for(var j = 0; j < factors.length;j++) {
var factor = factors[j];
if(isFactor(i,factor)) {
console.log(i + " match_one");
skipper = true
} else {
if(isFactor(i,factor)) {continue}
console.log(i)
}
}
}
}
}
matches([2,3],1,6)
Try breaking from the loops once you know that One factor matches.
function matches(factors, low, high) {
var skipper = false;
for(var i = low; i <= high; i++) {
if(allFactors(factors,i)){
console.log(i + " match_all")
} else {
for(var j = 0; j < factors.length;j++) {
var factor = factors[j];
if(isFactor(i,factor)) {
console.log(i + " match_one");
skipper = true;
// break here because we know that at least one factor matches
// and print "match_one"
break;
} else {
// number not matched
console.log(i);
}
}
}
// use skipper variable you assigned above to break out of outer loop
if(skipper){
break;
}
}
}
I am trying this code
var sum = 0
for (i = 0; i < 2000000; i++) {
function checkIfPrime() {
for (factor = 2; factor < i; factor++) {
if (i % factor = 0) {
sum = sum;
}
else {
sum += factor;
}
}
}
}
document.write(sum);
I am getting this error:
Invalid left-hand side in assignment
Change if(i % factor = 0) to if( i % factor == 0) and remove the function checkIfPrime() inside the for loop.
var sum = 0
for (i = 0; i < 2000000; i++) {
for (factor = 2; factor < i; factor++) {
if (i % factor == 0) {
sum = sum;
}
else {
sum += factor;
}
}
}
document.write(sum);
The function inside the loop is pointless.
it looks like your code outputs wrong result, for example prime numbers below 6 are 2, 3 and 5, their sum is 10, your code outputs 14 in this case.
Here is another code which outputs sum of primes below max value:
var sieve = [], primes = [], sum = 0, max = 5;
for (var i = 2; i <= max; ++i) {
if (!sieve[i]) {
// i has not been marked -- it is prime
sum += i;
for (var j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
console.log(sum);
credit to How to find prime numbers between 0 - 100?
function sumPrimes(num) {
var sum = 0;
for (var i = 2; i < num; i++) {
if (isPrime(i)) {
sum += i;
console.log(sum);
}
}
return sum;
}
function isPrime(num) {
if (num <= 1) return false;
else if (num <= 3) return true;
else if (num % 2 == 0 || num % 3 == 0) return false;
var i = 5;
while (i * i <= num) {
if (num % i == 0 || num % (i + 2) == 0) return false;
i += 6;
}
return true
}
console.log(sumPrimes(2000000));
Well, I did with 250 otherwise my screen would have frozen. First of you have to single out the prime numbers after placing them inside an empty Array, which I called primeNumbers from 2 to whatever number you want. Then I create a function that would filter the prime numbers and then add them all with a reduce method inside of another variable called sum and return that variable.
var primeNumbers =[];
for(var i = 2; i < 250; i++){
primeNumbers.push(i);
}//for loop
function isPrime(value){
for(var x=2; x< value; x++){
if(value % x===0){
return false;
}
}//for loop
return true;
}//function isPrime to filter
var sum = primeNumbers.filter(isPrime).reduce(function(acc, val) {
return acc + val;
}, 0);
console.log(sum);
when you are using a variable inside the loop you need to declare them. You have two points in this case
i is not declared
factor is not declare
Your if (i % factor = 0) is wrong, as pointed by some people above.
Also, you never call the checkIfPrime() method. I don't why you created them. Also, I improved your checkIfPrime() method. Please call sumOfPrimes() method in the code below and it should work. You can modify it according to your need
function sumOfPrimes()
{
var sum =0;
for (var i = 0; i < 2000000; i++)
{
var temp = Math.sqrt(i);
for (var factor = 2; factor < temp; factor++)
{
if (i % factor === 0)
{
sum += factor;
}
}
}
console.log(sum);
}
Try changing this line if (i % factor = 0) {
to
if (i % factor == 0) {
While working on problem 3 of Project Euler, I'm coming across a problem I can't seem to fix where javascript keeps freezing. Here's my code:
var is_prime = function(n) {
if (n === 1) {
return true;
}
if (n === 2) {
return true;
}
var list1 = []
for (i = 2; i < n; i++) {
list1.push(i);
}
for (i = 2; i < list1.length; i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
var list_of_primes = function(n) {
var list1 = [];
var list2 = [];
for (i = 2; i < n; i++) {
list1.push(i);
}
for (i = 2; i < list1.length; i++) {
if (is_prime(i)) {
list2.push(i);
}
}
return list2;
}
confirm(list_of_primes(1000))
I know my algorithm isn't the most efficient and that I'm just brute forcing the problem, but I'm just wondering what it is I'm doing wrong. I'm pretty sure the problem lies somewhere within this block of code:
for (i = 2; i < list1.length; i++) {
if (is_prime(i)) {
list2.push(i);
}
}
I think a potential problem is that my algorithm is taking too long and that is what is causing javascript to freeze. Is there anyway to get my problem to run long enough to give me the answer?
You could try this.
var is_prime = function(n) {
if (n == 1) {
return true;
}
if (n == 2) {
return true;
}
for (var i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
var list_of_primes = function(n) {
var list2 = [];
for (var i = 2; i < n; i++) {
if (is_prime(i)) {
list2.push(i);
}
}
return list2;
}
confirm(list_of_primes(1000))
Working fine in less than seconds. https://jsfiddle.net/LL85rxv5/
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Strictly speaking, 1 is not a prime number so be sure to update that in your code.
Not really sure why your code is timing out, it's just a bit longhand and has an unnecessary array (list1). Anyway, here's a pretty shortened version of the code that comes up with a list of prime numbers from 2 to n.
This isn't too efficient for a large number set because it checks every number individually.
var list_of_primes = function(n) {
var list = [];
for (i = 2; i < n; i++) {
if (is_prime(i)) {
list.push(i);
}
}
return list;
}
function is_prime(i) {
for (var c = 2; c <= Math.sqrt(i); ++c)
if (i % c === 0)
return false;
return true;
}
If you want a bit more efficiency, look into the Sieve of Eratosthenes which can handle much larger sets:
// Credit: http://stackoverflow.com/a/15471749/1265817
var eratosthenes = function(n) {
// Eratosthenes algorithm to find all primes under n
var array = [], upperLimit = Math.sqrt(n), output = [];
// Make an array from 2 to (n - 1)
for (var i = 0; i < n; i++) {
array.push(true);
}
// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 2; i <= upperLimit; i++) {
if (array[i]) {
for (var j = i * i; j < n; j += i) {
array[j] = false;
}
}
}
// All array[i] set to true are primes
for (var i = 2; i < n; i++) {
if(array[i]) {
output.push(i);
}
}
return output;
};
Working examples: https://jsfiddle.net/daCrosby/wfgq28no/
i is a global variable within is_prime function, which interferes with instance used in list_of_primes function. Fix by declaring i as local like this...
var is_prime = function(n) {
var i; // <~~ declare i as local variable here
if (n === 1) {
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();