The isPrime() function returns true if a number is a prime number and it returns false if not. The loop should go through 2 to 500 backward and run it in the isPrime() function. If the number is not a prime number the loop should continue to the next loop iteration. And also, for the number which is a prime number, it should output in the paragraph's textContent, but the continue is not working.
Here is the code:
let i = 500;
const para = document.createElement('p');
function isPrime(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return false;
}
}
return true;
}
// Add your code here
while( i >= 2 ){
if( isPrime(i) === false){
continue;
} else{
para.textContent = `${i}` + "</br>";
}
i--;
}
And here is the fiddle: https://jsfiddle.net/au9o2ftn/1/
You can simply do this:
let i = 500;
function isPrime(num) {
for (let i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
while (i >= 2) {
if (isPrime(i)) {
console.log(i + " is prime!");
}
i--;
}
without continue...
The problem is that when isPrime(i) in your original code returns true, it continue directly and didn't finish i--. As a result, it becomes a dead loop with infinitely checking isPrime(500).
Or, if you wish to keep continue, put i-- before the continue statement.
Related
Hello I am trying to refactor my function but it doesn't seem to be working properly. It works fine normally which is the commented code. Am I writing this wrong or is there a fundamental flaw in my code?
function isPrime(num) {
// if (num <= 1){
// return false
// } else {
// for(var i = 2; i < num; i++){
// if(num % i === 0) return false;
// }
// }
num <= 1 ? false : {
for(let i = 2; i < num; i++){
num % 1 === 0 ? false
}}
return true;
}
Thanks
As far as I can tell, no language having the ternary operator allows running a block of statements, which is what you are doing. The ternary operator is a shorthand version of:
let result;
if (<condition>)
result = resultTrue;
else
result = resultFalse;
Unless JavaScript stabs be in the back on this one, for is a statement that doesn't return anything, and therefore cannot be used the way you want.
The best you could do, I guess, would be:
function isPrime(num) {
if (num <= 1) {
return false;
}
for(var i = 2; i < num; i++) {
if(num % i === 0) return false;
}
}
The else part omitted since hitting the line after the if necessarily means that the condition for it was not met.
Technically what you have can be brought to life with an IIFE:
function isPrime(num) {
return num <= 1 ? false :
(n => {
for (let i = 2; i < n; i++) {
if (n % i === 0) return false;
}
return true;
})(num)
}
for (let i = 0; i < 10; i++) {
console.log(i, isPrime(i));
}
Now it works and there is a ternary operator inside.
Even the attempt without return can be done, just you need isPrime made into an arrow function:
let isPrime = num => num <= 1 ? false :
(n => {
for (let i = 2; i < n; i++) {
if (n % i === 0) return false;
}
return true;
})(num);
for (let i = 0; i < 10; i++) {
console.log(i, isPrime(i));
}
Tadaam, the num <= 1 ? false : part is literally there in the first line, without that nasty return.
But realistically this is not how isPrime should be implemented, your very first attempt is the best one so far.
If you want an actual improvement, use the fact that divisors come in pairs. If x is a divisor of num, then num/x is also divisor of num. So if you were looking for all divisors of num, you would find them in pairs as soon as x=num/x=sqrt(num), so it's enough to check numbers between 2 and Math.floor(Math.sqrt(num)), inclusive. As you preferably don't want JS to calculate this number in every iteration (when checking the condition), you could count downwards, so
for (let i = Math.floor(Math.sqrt(num)); i >= 2; i--)
everyone.I was practicing on code wars and solving a problem aimed on prime numbers.I comleted it, but having submitted the program i get the message Execution Timed Out (12000 ms); Here is the program: `
function isPrime(number) {
let counter = 0;
for (let i=1;i<=number;i++){
if (number % i == 0) {
counter++;
}
}
if (counter == 2) {
return true
} else return false
}
function getPrimes(start, finish) {
let a = [];
let b = [];
if (start == 0 && finish == 0) {
return b;
}
if (start < finish) {
for (let i=start;i<=finish;i++){
a.push(i);
}
for (let j=0;j<a.length;j++) {
if (isPrime(a[j])) {
b.push(a[j]);
}
}
return b;
}
else if (start > finish) {
for (let i=finish;i<=start;i++){
a.push(i);
}
for (let j=0;j<a.length;j++) {
if (isPrime(a[j])) {
b.push(a[j]);
}
}
return b;
}
}
`
There are two funcs, the first one returns true if the number is prime and false if not.
and the second one takes start and finish like array borders and you need to return sorted array of prime numbers in these diapazon.I will be grateful for your help =)
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.
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 would like to break the for loop here and return false so it doesn't keep testing the condition with the rest of the array elements and return the value I don't want it to return.
It's a code that's supposed to test the divisibility of the number by prime numbers that are smaller than 100.
var primenumbers = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97];
var primetest = function (a) {
for (i = 0; i < primenumbers.length; i += 1) {
if ((a !== primenumbers[i]) && (a % primenumbers[i] === 0)) {
return false;
} else {
return true;
}
}
}
Your problem is that both return statements are inside the loop so the loop will always only execute the first iteration and then return. It will never test for anything other than the first element in the array.
Solution: Move one of the statements out of the loop so that all array elements are checked and if none match, then the other return statement is executed:
var primenumbers = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97];
var primetest = function (a) {
for (i = 0; i < primenumbers.length; i += 1) {
if ((a !== primenumbers[i]) && (a % primenumbers[i] === 0)) {
return false;
}
}
return true;
}
The problem with your code is not that it won't exit when you want it to, it's that it exits even when you don't want it to.
Don't return anything in the else case, instead wait until the loop has finished to return the result that no match was found in the loop:
var primenumbers = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97];
function primetest(a) {
for (i = 0; i < primenumbers.length; i += 1) {
if ((a !== primenumbers[i]) && (a % primenumbers[i] === 0)) {
return false;
}
return true;
}
}