Function called but without reference to parameter - javascript

I wrote the following code and something strange happens. The last line fizzbuzz(15) where I call the function is necessary to get the loop to run, but does not take into account the parameter, in this case, 15. How can I integrate the parameter into my function?
function fizzbuzz(num) {
for(num = 0; num < 20; num++) {
if(num % 3 === 0 && num % 5 === 0){
result = "fizzbuzz";
}
else if(num % 3 === 0){
result = "fizz";
}
else if(num % 5 === 0){
result = "buzz";
}
else if(num % 3 !==0 && num % 5 !==0){
result = num;
}
console.log(result);
}
}
fizzbuzz(15);

for(num = 0; num < 20; num++) {
You're changing it back to 0 here every time you run this. It doesn't matter what you pass in if you keep assigning zero.
I suppose this is what you're after:
for(num; num < 20; num++) {
Or, if you are after setting the number of iterations, then this:
for(var i = 0; i < num; i++) {
(and then change all of your references inside of the loop from num to the more idiomatic i)

Related

Why always return "None" string, like my if statment was always false?

My second approach to learning JS.
Maybe someone will tell me why I always get "none".
Thank you for any help.
const reverseFactorial = (num) => {
for (let i = 1; num > 1; num = num / ++i) {
if (num === 1) return `${i}`
}
return 'None'
};
console.log(reverseFactorial(120))
check your if condition and for loop condition.num>i is your for loop condition so when i=1 in for loop it will immediately exit the for loop and not enters into the if condition so your if condition is never satisfied that's why you always get none.
so change your for loop condition to
num>=1;
Here's a working demo
Code Snippet
const reverseFactorial = (num) => {
for (let i = 1; num >= 1; num = num / ++i) { // condition updated to "num >= 1"
if (num === 1) return `${i}`
}
return 'None'
};
console.log('reverseFactorial(120) gives: ', reverseFactorial(120))
Sure it is possible to perform this also with the ternary operator, you have to change the internal 'if' check with an assignment to a temporary variable (let's call it 'result') which will be holding the temporary result at each iteration until the num equals one (num === 1) condition is met or num is no longer greater than nor equal to one (num >= 1); at that point, the for loop will end and the result is returned with the associated 'reversefactorial' value or 'None' value:
const reverseFactorial = (num) => {
// this avoids exceptions if num < 1 as you always return a valid value
// by returning zero, the function is reporting an invalid num argument
result = 0
for (let i = 1; num >= 1; num = num / ++i) { // condition updated to "num >= 1"
result = (num === 1) ? `${i}` : 'None'
}
return result
};
console.log('reverseFactorial(120) gives: ', reverseFactorial(120))
You can also speed the loop by taking everything out like this:
const reverseFactorial = (num) => {
// take into account num < 1
if (num < 1) {
i = 0;
num = 1;
}
else i = 1;
for (;num >= 1; num = num / ++i) { // condition updated to "num >= 1"
if (num === 1) break;
}
return (num === 1) ? `${i}` : 'None'
};
console.log('reverseFactorial(120) gives: ', reverseFactorial(120))
Though, as you can see, it is now more cumbersome to take into account invalid num entries with the starting if to correctly set the initial value for i; anyway this function should be faster than the previous one, the more the higher num is as we are taking the assigment out of the loop.

Why does repeat function not work the second time?

The challenge is to return an array that follows an arrow pattern when given a number. For example:
arrow(3) ➞ [">", ">>", ">>>", ">>", ">"]
I have almost completed it but it repeats the middle value in the array twice.
function arrow(n) {
var arr = [];
var num = 1;
while(num <= n) {
arr.push(">".repeat(num));
num++;
}
while(num > 0) {
arr.push(">".repeat(num - 1));
num--;
}
return arr;
}
console.log(arrow(3));
So then I changed it to this (for the second repeat I changed it to num - 2 but it says an error).
function arrow(n) {
var arr = [];
var num = 1;
while(num <= n) {
arr.push(">".repeat(num));
num++;
}
while(num > 0) {
arr.push(">".repeat(num - 2));
num--;
}
return arr;
}
console.log(arrow(3));
Can someone explain to me why this doesn't work?
Your function does not work because you start the second loop when num is equal to n + 1 (which causes the middle value to be added twice) and do not end the loop until num is 0 (which causes an empty string to be appended to the result). For a simpler solution, you can use Array.from with a bit of arithmetic.
function arrow(n) {
return Array.from({length: n * 2 - 1}, (_,i)=>">".repeat(i < n ? i + 1 : n * 2 - 1 - i));
}
console.log(arrow(3));
The first one does not work because "num" is incremented a last time and thus equals "n + 1" when the code goes out from the while loop.
So if "n" = 3, when the code executes the first "while(num > 0) {", num will equal 4. So 4 - 1 = 3 repetition of the arrow.
So, to fix it :
function arrow(n) {
var arr = [];
var num = 1;
while(num <= n) {
arr.push(">".repeat(num));
num++;
}
num--; // add this line
while(num > 0) {
arr.push(">".repeat(num - 1));
num--;
}
return arr;
}
console.log(arrow(3));
The error with the first solution is that when num equals 3, you increment it to 4 in the while loop. When the second while loop runs, num - 1then equals 3.
In the second solution, num - 2 will equal -1 during the fourth iteration, which throws an error.
A for-loop may be easier to control here:
function arrow(n) {
var arr = [];
var num = 1;
for (let i = 1; i <= n; i++) {
arr.push(">".repeat(i))
}
for (let i = n - 1; i > 0; i--) {
arr.push(">".repeat(i));
}
return arr;
}
The issue with your second function :
when you were using the second while loop, the value of num was decreasing by 1 in each loop.
when the loop value of num comes to 1 , and and you tried to use arr.push(">".repeat(num - 2)); , then n-2 = -1 , but repeat(-1) is invalid function.
Solution:
I think in between two while loop, use num--; to decrease the value of num by 1. it will solve your problem.
function arrow(n) {
var arr = [];
var num = 1;
while(num <= n) {
arr.push(">".repeat(num));
num++;
}
num --;
while(num > 1) {
arr.push(">".repeat(num - 1));
num--;
}
return arr;
}
console.log(arrow(3));
so when your loop get the last element number == 1
the repeat function (num-2) will not work
for this challenger i simply put a (number--;) in the middle of the While loops
i hope that work.
function arrow(n) {
var arr = [];
var num = 1;
while(num <= n) {
arr.push(">".repeat(num));
num++;
}
num--; // take 1 out
while(num > 1) {
arr.push(">".repeat(num -1));
num--;
}
return arr;
}
console.log(arrow(3));

Find and print the biggest prime number (JS)

I'm studying node.js and have some interesting task - Write a program that finds and prints the biggest prime number which is <= N.
Input // Output - 13 // 13
126 // 113
26 // 23
In last course with java i have the same task and my code is really simple:
import java.util.Scanner;
public class BiggestPrimeNumber {
public static void main(String[] args){
int n;
Scanner in = new Scanner(System.in);
n=in.nextInt();
while(prim(n) == false){
n--;
}
System.out.println(n);
}
public static boolean prim(int m){
int n=m;
for(int i=2;i<n;i++){
if(n%i == 0){
return false;
}
}
return true;
}
}
I try similar way to test it, but I'm don't have idea how to convert it:
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
Can you help me, because I'm really have problem with js using in console.
I think this is what you want. You only need to declare a function and use it as you are doing.
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(m) {
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
}
If your running it with NodeJS in console, you can save it in a file called prime.js (for example) and execute it with: node prime.js.
You can pass parameters to the script like: node prime.js 126 and then get them in the code. That will be something like that:
const args = process.argv;
let n = args[2];
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(m) {
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
}
You're pretty close. First off, you don't have isPrime defined. Second, if you were to paste all of your code into the browser console, it isn't going to like that you are defining n twice. I also cleaned up your isPrime bit of code.
let n = 100;
let result = n;
const isPrime = num => {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num !== 1 && num !== 0;
}
while (isPrime(result) === false) {
result -= 1;
}
console.log(result + " is the next prime below " + n);
Also, remember that javascript is not a compiled language, so unless you are defining your function in a class, the browser will interpret the code sequentially. Therefore, you have to have isPrime defined before you use it.
The algorithm to find the nearest prime number can be further optimized. All prime numbers are of the form 6k+1 or 6k-1 except the numbers 2 and 3. Also, instead of checking all the way to the number the check can be made till Sqrt(n). Here is the modified isPrime function:
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(num) {
if (num <= 1) return false;
if (num < 4) return true;
if (num%2 === 0 || num%3 === 0) return false;
for (var i = 5; i*i <= num; i+=6) {
if (num % i === 0 || num % (i + 2) === 0)
return false;
}
return true;
}

Why is this code looping infinitely?

I'm trying to write a program in JavaScript that generates 100 random numbers and checks the primality of each. The program does just that, except for some reason it doesn't stop at 100 and just loops infinitely. I'm sure I made some simple novice mistake, but for some reason I can't see it. Any advice?
My code:
function isPrime(n) {
if (n < 2 || n % 1)
return false;
var r = Math.sqrt(n);
for (i = 2; i <= r; i++)
if (n % i === 0)
return false;
return true;
}
for (i = 0; i < 100; i++) {
var temp = Math.floor((Math.random() * 100) + 1);
if (isPrime(temp))
console.log(temp + " is a prime number!");
else
console.log(temp + " is not a prime number.");
}
Thanks!
You need to declare i variable in for-loops:
(var i = 0; i < 100; i++) ...
otherwise it is defined in global scope and it is shared between for-loop and isPrime function.
madox2 is correct that you should declare i in the for loop, however I think the reason the loop itself is infinite is because by only doing i=0 in the loop, and then for (i = 2; i <= r; i++) in the function the loop calls, you are resetting i every iteration
You should change your code to declare i within the scope of both loops separately, like so:
function isPrime(n) {
if (n < 2 || n % 1)
return false;
var r = Math.sqrt(n);
for (var i = 2; i <= r; i++)
if (n % i === 0)
return false;
return true;
}
for (var i = 0; i < 100; i++) {
var temp = Math.floor((Math.random() * 100) + 1);
if (isPrime(temp))
console.log(temp + " is a prime number!");
else
console.log(temp + " is not a prime number.");
}

for/while loop for reading user input

I'm kinda new to programming and I got this question in a quiz. I need to write a JavaScript program to read 10 positive values from the user, and then sum only the multiples of 3 and 5.
I couldn't even finish the code. help?
var x = new Array ();
var total;
x.push(parseFloat(window.prompt("enter a value",""),));
for (x.length<=10; i=0; i<10; i++) {
total += x[i]
}
else{
document.write(total);
}
You need to put your prompt function inside for loop and add check if number is multiply by 3 or 5.
var total;
for (var i=0; i<10; i++) {
var num = parseFloat(window.prompt("enter a value",""));
if (num % 3 == 0 || num % 5 == 0) {
total += num;
}
}
document.write(total);
UPDATE:
var total;
var i = 0;
while (i<10) {
var num = parseFloat(window.prompt("enter a value",""));
if (num >= 0 && (num % 3 == 0 || num % 5 == 0)) {
total += num;
i++;
}
}
document.write(total);
thanks, i did set total=0 so that after the sum it prints out a value instead of NaN
var total = 0;
var i = 0;
while (i < 10) {
var num = parseFloat(window.prompt("enter a value", ""));
if (num >= 0 && (num % 3 == 0 || num % 5 == 0)) {
total += num;
i++;
}
}
document.write(total);

Categories

Resources