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;
}
}
}
Related
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.
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>
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));
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(', '));
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();