for/while loop for reading user input - javascript

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);

Related

Sum All Primes Below a Given Number | Intermediate Javascript Algorithm | Recursion

Question
A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.
My Attempt
const isPrime = a => {
for(let i = 2; i < a; i++)
if(num % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
sumPrimes(10);
The Problem
It says: 'Num is not defined'
I am not sure if there are other errors.
My Question
Please could you help me find the error, and fix the code to solve the algorithm?
This was a simple syntax error identified by #Jonas Wilms (upvote him in the comment above :))!
By replacing the 'a' with 'num' the function was fixed.
const isPrime = a => {
for(let i = 2; i < a; i++)
if(a % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
console.log(sumPrimes(10));
this simple function may help you,
function isPrime(num) {
for (var i = 2; i < num; i++)
if (num % i === 0) return false;
return num > 1;
}
function sumPrimes(num) {
let tot = 0;
for (let i = 0; i < num; i++)
if (isPrime(i))
tot += i;
return tot;
}
console.log(sumPrimes(10));

javascript - functions and equations confusion

var number = prompt('Input a number!');
var n = number;
function getList() {
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0)
console.log (n);
}
}
console.log(getList());
console.log((n*(n+1))/2);
//equation for summation: (n*(n+1))/2
I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.
I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?
The answer is supposed to be 60. Any clue? Thanks!
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 === 0 || n % 5 === 0)
sum += n;
}
console.log(sum);
Use a variable to add the numbers and return it after for loop.
Below it the exapmle.
function getList() {
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0) {
sum += n;
}
}
return sum;
}
console.log(getList());
Two things:
Just return the sum from your getList function
Make sure your prompt input is converted to integer otherwise it will be treated as a string and your n*(n+1)/2 will be wrong
var number = parseInt(prompt('Input a number!'));
var n = number;
function getList() {
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0) {
console.log (n);
sum += n;
}
}
return sum;
}
console.log(getList());
console.log(n, (n*(n+1))/2);
If you want an equation :)
function sumOfNumbersDivisibleBy3Or5(n) {
const by3 = Math.floor(n/3),
by5 = Math.floor(n/5),
by3And5 = Math.floor(n/3/5);
return 3*by3*(by3+1)/2 + 5*by5*(by5 + 1)/2 - 3*5*by3And5*(by3And5 + 1)/2
}
console.log(sumOfNumbersDivisibleBy3Or5(17))
var number = prompt('Input a number!');
function getList() {
var sum = 0;
for (var n = 1; n <= number; n++) {
if (n % 3 == 0 || n % 5 == 0)
sum+=n;
}
return sum;
}
console.log(getList());
it will return sum of all the number which is divisible by 3 or 5 in between 1 and entered number

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.");
}

How do you make every 9th element in Math.random array to be the same element?[javascript]

I have this bit of code here
<script language='javascript' type='text/javascript'>
var imagesArray = ["1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png","9.png","10.png","11.png","12.png","13.png","14.png","15.png","16.png","17.png","18.png","19.png","20.png","21.png" ];
var newArray = new Array(100);
for (i = 0; i < 100; i++)
{
if (i % 9 === 0)
{
}
else
{
newArray[i] = imagesArray[Math.floor(Math.random() * imagesArray.length)];
}
}
</script>
the idea behind is that i need it so that every 9th number that would be randomly chosen would remain the same, but i have no idea what do i put there so it would work.
Do you got any advice?
Thanks!
Here is a sample of what you can do :
First fill your array with Math.random() or whatever you want.
imagesArray[i] = Math.floor((Math.random() * 10) + 1);
If you want the value to be the same every 9 elements , use a loop starting at 9 and going through every 9 elements with i+9
for(var i = 9; i < yourArray.length ; i = i + 9){
imagesArray[i] = imagesArray[9];
}
Actually you can start the loop at 18 as well
Demo
Try defining a variable outside of for loop to store value at first i % 9 === 0
var newArray = new Array(100), ninth = null;
for (i = 0; i < 100; i++) {
newArray[i] = imagesArray[Math.floor(Math.random() * imagesArray.length)];
if (i % 9 === 0 && ninth === null && i === 9) {
ninth = newArray[i]
};
if (i % 9 === 0 && i >= 9) {
newArray[i] = ninth;
};
}

Function called but without reference to parameter

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)

Categories

Resources