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
Related
I am stuck in the sumAll exercise from the Fundamentals 4 portion of the Odin Project. I managed to pass the test in which I need the result to be ‘ERROR’. However, I cannot figure out the correct code to pass the other tests. Where did I go wrong?
This is the exercise:
const sumAll = require(’./sumAll’)
describe(‘sumAll’, function() {
it(‘sums numbers within the range’, function() {
expect(sumAll(1, 4)).toEqual(10);
});
it(‘works with large numbers’, function() {
expect(sumAll(1, 4000)).toEqual(8002000);
});
it(‘works with larger number first’, function() {
expect(sumAll(123, 1)).toEqual(7626);
});
it(‘returns ERROR with negative numbers’, function() {
expect(sumAll(-10, 4)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, “90”)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, [90, 1])).toEqual(‘ERROR’);
});
});
My code:
const sumAll = function(a, b) {
const arr = [];
if (a < b) {
while (a <= b) {
arr.push(a++);
}
} else if (b < a) {
while (b <= a) {
arr.push(b++);
}
} else {
arr.push(a);
}
if (a < 0 || b < 0) {
return “ERROR”;
} else if (typeof a !== NaN || typeof b !== NaN) {
return “ERROR”;
}
return arr.reduce((a, b) => a + b);
}
module.exports = sumAll
I made in this way:
const sumAll = function (x, y) {
if (x > 0 && y > 0 && typeof x === 'number' && typeof y === 'number') {
var valorx = x;
var valory = y;
var total = 0;
if (x < y) {
for (var i = valorx; i <= valory; i++) {
total += i;
}
return total;
} else if (x > y) {
for (var i = valory; i <= valorx; i++) {
total += i;
}
return total;
}
} else {
return 'ERROR'
}
}
module.exports = sumAll
this how it work for me
const sumAll = function (startN, endN) {
//create variable to store total sum
let sum = 0;
check if input parameter in number:
if (typeof startN != "number" || typeof endN != "number") return "ERROR";
check if input numbers greter than 0:
else if (startN < 0 || endN < 0) return "ERROR";
and last check is, if last number greater than the first number then initial number will be the last number otherwise start number will be the initial:
else if (startN < endN) {
for (i = startN; i <= endN; i++) {
sum += i;
}
} else {
for (i = endN; i <= startN; i++) {
sum += i;
}
}
then return sum:
return sum;
};
you can make all these in one check but this are more readable.
That's how i did it. Quite similar but i avoided using for loops.
const sumAll = function(n,m) {
if (n<0 || m<0 || typeof(m) !== 'number' || typeof(n) !== 'number'){
return 'ERROR'
}else {
if(n<m){
n1 = n
n2 = m
}else{
n1 = m
n2 = n
}
return (n1+n2)*(n2/2)}
};
I first checked whether the input is valid, then decided the values of the two variables depending on which is bigger and finally calculated the sum.
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>
// 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.
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;
}
var enteredValue = prompt("enter a number");
enteredValue = enteredValue + 0;
console.log(isPrime(enteredValue));
function isPrime(num) {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
} else {
return true;
}
}
}
Can anyone tell me what I'm doing wrong? The code is always returning false.
You need to move the return of true out side of the loop, because you need to check all factors before returning true.
var enteredValue = +prompt("enter a number");
console.log(isPrime(enteredValue));
function isPrime(num) {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
Your method should return true outside of your for loop. With your example you are retuening in first iteratin, by entering else block.
This will work:
function isPrime(num) {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false; // return if it's not a prime
}
}
return true; // return only if it's a prime number
}
You can also check other prime solutions in this post.