JavaScript Odd Number Sorter Coding Challenge [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Ok so I'm working on learning JavaScript and I came across a Coding Challenge question which I can not solve. It gives me the outline/skeleton of the format I should use and wants me to find the odd numbers from 1-5000.
Starting with the basic function given below, write a function called sumOddNumbers that will print to the console and return the sum of all the odd numbers from 1 to 5000. Consider using a loop, and don't forget to call the function afterwards!
~ Format ~
function sumOddNumbers() {
var sum = 0;
// Your code here
console.log(sum);
return sum;
}

There is no need for a loop:
console.log(5000**2/4);
If 5000 is a dynamic input to your function, then the formula is as follows:
function sumOddNumbers(n) {
return (n + n%2)**2/4;
}
console.log(sumOddNumbers(5000));
If really it has to be done with a loop, and according to the template (which is not very nice BTW):
function sumOddNumbers() {
var sum = 0;
for (let i = 1; i <= 5000; i+=2) {
sum += i;
}
console.log(sum);
return sum;
}
sumOddNumbers();

let sum = 0;
for (let i = 1; i < 5000; i += 2) {
sum += i;
}

let sum = 0;
for (let i = 0; i < 5000; i++) {
if (i % 2 !== 0) {
sum += i;
}
}

function sumOddNumbers(max) {
let sum = 0;
for(let i = 1; i <= max; i+=2){
sum += i;
}
console.log(sum);
return sum;
}
sumOddNumbers(5000);

Related

Array in each position successively Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I've got trouble with arrays. I'm trying to iterate elements for each position in the array using javascript.
so, I need to do that on the first position, be a value [1]. On the second position, [2, 3, 4]. on the third position, [5,6,7,8,9] and successively two by two.
My attempt was did a for loop:
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
console.log(`${i} ${j}`)
}
}
But while looping, the indices (i) repeat with (j).
What to do?
Try this code.
var counting = 1;
for (let i = 1; i <= 5; i = i + 2) {
var str = "";
for (let j = 1; j <= i; j++) {
str += `${counting} `;
counting++;
}
console.log(str);
}

How to display the prime numbers that are less than the (limit) in ascending order by using the function showPrimes() and parameter (limit) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
<script type = "text/javascript">
function showPrimes(limit) {
for (let number = 2; number <= limit; ++number) {
let isPrime = true;
}
}
</script>
Above the code, I am currently working on so far. Not sure how to continue.
function getPrimes(limit) {
var sieve = [], i, j, primes = [];
for (i = 2; i <= limit; ++i) {
if (!sieve[i]) {
primes.push(i);
for (j = i << 1; j <= limit; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
console.log(getPrimes(100));

get all 3 digit number whose sum is 11 or we can say module is 1 in JS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
In response I want all 3 digit numbers whose sum is 11 and also gives module 1 and
also want to know how can I push 000 in array in js.
For example number = 128, sum = 11 and module(remainder) = 1.
Like this I want all that numbers in array.
Can anyone share the logic for the same.
Thanx in advance.
I'm not sure what the second check is supposed to be (the modulus of something has to be 1). If that is supposed to be that the modulus of all digits of the number has to be 1, here is how you could do it:
var results = [];
for (let i = 1; i < 10; i++) {
for (let j = 0; j < 10; j++) {
for (let k = 0; k < 10; k++) {
if (i + j + k === 11 && i % j % k === 1) {
results.push(i.toString() + j.toString() + k.toString());
}
}
}
}
console.log(results);
OR:
var results = [];
for (let i = 100; i < 1000; i++) {
const [one, two, three] = i.toString().split('').map(i => +i);
if (one + two + three === 11 && one % two % three === 1) {
results.push(i.toString());
}
}
console.log(results);
Basically just go through all the possible combination and do the checks on each number.
Is this what you want?
var arr=[1,128,15];
var remainder = 127;
var result = arr.filter(function(i) {
var str=i.toString().split('');
var sum=0;
str.forEach(function(c) { return sum+=Number(c); });
return sum===11 && (i%remainder)===1;
});
and more fancy and ES6:
const arr=[1,128,15];
const remainder = 127;
const result = arr.filter(i=>{
const sum=i.toString().split('').reduce((s,v)=>(+v)+s,0);
return sum===11 && (i%remainder)===1;
});
You could take a brute force approach and check the sum with eleven. A check with the remainder is not necessary, because 11 has always a rest of one, if divided by ten.
const
getSum = v => [...v.toString()].reduce((a, b) => a + +b, 0),
values = [];
for (let i = 1; i < 1000; i++) {
if (getSum(i) === 11) values.push(i);
}
console.log(values);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Using a variable inside the Math.random function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am working on a piece of code which make an array full of numbers with the amount of numbers i want, but instead of this beeing static with 16 numbers i tried to change 16 to a variable but the math.floor/randome cant read it it only spits out Not a number wierdly enough.
EDIT: with 16 put in it works, but i cant use a variable (declared in the same function ofc)after i console.log the variable it shows it as a number but then my browser freezes
Is There anyone who knows how to change this
while(arr.length < pictures.length) {
var randomenumber = Math.floor((Math.random()* 16));
if(arr.indexOf(randomenumber) > -1) {
continue;
}
arr[arr.length] = randomenumber;
}
//cheat sheet
for(var i = 0; i < arr.length ; i++) {
document.write(arr[i]);
document.write("<br/>");
}
I don't see any issues if you use var length = 16 and Math.floor((Math.random() * length)).
Working snippet:
var arr = [], length = 16;
while(arr.length < length) {
var randomenumber = Math.floor((Math.random() * length));
if(arr.indexOf(randomenumber) > -1) {
continue;
}
arr[arr.length] = randomenumber;
}
//cheat sheet
for(var i = 0; i < arr.length ; i++) {
document.write(arr[i]);
document.write("<br/>");
}
You will need to parse it in integer using parseInt.
var num = 16;
var randomenumber = Math.floor((Math.random() * parseInt(num)));

Optimize javascript if else 18 times [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am trying to create a golf scorecard and are able to do so like this:
if(i == 0){
totalpoints = pp0[0];
} else if(i == 1){
totalpoints = pp0[0]+pp0[1];
} else if(i == 2){
totalpoints = pp0[0]+pp0[1]+pp0[2];
} else if(i == 3){
totalpoints = pp0[0]+pp0[1]+pp0[2]+pp0[3];
}....
This off course goes on 18 times? making each line even longer... How can I do this more optimized?
Hoping for help and thanks in advance :-)
Where i is your existing variable:
var totalpoints = 0;
for(var j = 0; j < i; j++) {
totalpoints += pp0[j];
}
This is pretty much what arrays were invented for!
you can use this:
for (var j=0;j<i+1;j++) {
totalpoints += pp0[j];
}
for (j=0; j<=i; j++) {
totalpoints += pp0[j];
}
basically what you are doing is doing a sum, so a doing a method might be a good start:
function sum(counter)
var sum =0;
for(var i = 0; i < counter ; i++) {
sum+= pp0[i];
}
return sum;
}
you can try writing a loop.
totalPoints = 0;
for(var i=0;i<j;i++)
{
totalPoints += pp0[i];
}
It looks like you just want to add up the first i values in the pp0 array, so use a loop:
var totalpoints = 0;
for (var index=0; index<i; index++) {
totalpoints += pp0[index]
}
It's like you're doing a sum, so you can use the built-in reduce function in JavaScript:
totalpoints = pp0.reduce(function (prev, cur) {
return prev + cur;
}, 0);
This will go through all elements in pp0 and return a sum. If, however, you want only the first n parts of pp0, use a slice:
totalpoints = pp0.slice(0, n).reduce(function (prev, cur) {
return prev + cur;
}, 0);
See mdn for details and browser compatibility.
Note:
This solution assumes that you're using a real array (Array.isArray()) and relatively new browser features.

Categories