Is there a way to make certain for loop iterations different? - javascript

JavaScript. Is there a way to get a for loop do things slightly differently on every second (fifth etc.) iteration from what it is doing "by default"?
for (var i = 0; i < n.length; i++) {
a += 5;
b += a;
}
What if I want to add to a not 5 but 10 on every second iteration and add to b not a but b itself on every fifth iteration of the loop? Is this doable? Thank you!

Use the modulus operator % to find out whether i is evenly divisible by the "every Nth" value.
This will run both clauses on the first (zeroth) iteration, since zero is so divisible; you might want i % 2 == 1 and i % 5 == 4 instead, depending.
for (var i = 0; i < n.length; i++) {
if(i % 2 == 0) {
a += 5;
}
if(i % 5 == 0) {
b += a;
}
}

You can do the following,
for (var i = 0; i < n.length; i++) {
if(i%2 === 0) {
a += 10;
} else {
a += 5;
}
if(i%5 === 0) {
b+= =b;
} else {
b += a;
}
}

maybe you can try this:
for (var i = 0; I <n.length; i++){
if( i + 1 / 2) {
a += 10;
b += a
}else if ( i + 1 / 5) {
a += 5;
b += b
} else {
a += 5;
b += a;
}
}

Related

Find the next greater prime of a given number

Here's the code i wrote to solve the problem:
let isPrime = function(n) {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
};
function nextPrime(num) {
let newNum = num;
for (let i = 0; i < newNum; i++) {
if (!isPrime(newNum)) {
newNum += 1;
} else if (isPrime(newNum)) {
return newNum;
}
}
};
My plan is:
// increment the num by 1 and check if that new num is prime;
// if not, increment again and check again. Repeat the process untill prime is found.
Input and (expected output is commented):
console.log(nextPrime(2)); // 3
console.log(nextPrime(3)); // 5
console.log(nextPrime(7)); // 11
console.log(nextPrime(8)); // 11
console.log(nextPrime(20)); // 23
console.log(nextPrime(97)); // 101
The output i'm getting;
2
3
7
11
23
97
I'd like to know where exactly my implementation is wrong. Also, i'd like the code to be without fancy methods because i'm new to all this. Thank you!
The assignment newNum = num precisely does not make newNum a new number, but the same ! This is why the function returns immediately when the input argument is prime.
By the way, the loop would be much cleaner as
do
{
newNum += 1;
} while (!isPrime(newNum));
function nextPrime(previousPrime) {
const value = previousPrime;
if (value > 2) {
var i, q;
do {
i = 3;
value += 2;
q = Math.floor(Math.sqrt(value));
while (i <= q && value % i) {
i += 2;
}
} while (i <= q);
return value;
}
return value === 2 ? 3 : 2;
}

Why does the for loop in my code restart automatically?

I'm trying to output the pascal triangle. So i stored the previous output in an array(for ex:1,2,1).Then i'm trying to obtain sum of two elements in array(like array[0]+array[1] then array[1]+array[2]).But the loop which i use for getting the sum restarts on it's own (i.e after o is equal to array.length-1 o becomes equal to zero.
Also any help with proper code formatting and how i could do this in a better way is welcome.
I have tried setting array length to zero when the variable o is equal to array length but then too loop starts to run again from zero.
var count=0,sum=0;
let arr=[],arr1=[],arr2=[];
//For Rows
for (let i = 1; i <= 4; i++) {
//For Spaces
for (var k = 4; k >= i; k--) {
document.querySelector('#a').innerHTML += " ";
}
//For addition logic (This Restarts automatically)
for (let j = 1; j <= i; j++) {
if (j == 1 || j == i) {
document.querySelector('#a').innerHTML += " " + 1;
} else {
for (let o = 0; o < arr2.length; o++) {
sum += parseInt(arr2[o]);
if (o % 2 == 1 && i > 3) {
document.querySelector('#a').innerHTML += " " + sum;
sum = parseInt(arr2[o]);
}
}
document.querySelector('#a').innerHTML += " " + sum;
}
count += 1;
}
if (i > 1) {
sum = 0;
arr.length = 0, arr1.length = 0, arr2.length = 0;
arr.push(document.querySelector('#a').innerText);
arr1 = Array.from(arr[0]);
arr2 = arr1.filter(rem)
function rem(value) {
return value > 0;
}
var temp = 0;
while (temp < count - i) {
arr2.shift();
temp++;
}
}
document.querySelector('#a').innerHTML += "<br/>";
}
<html>
<head></head>
<body>
<div id="a"></div>
</body>
</html>
1
1 1
1 2 1
1 3 3 1
Expected Result
1
1 1
1 2 1
1 3 3 6 3 1
Actual Result
You could take a loop for getting the wanted length of the array and another for calculating the sum of two elements of the array.
This approach starts with a single element and takes for every round one at start and one at the end and all other value from the array.
var length = 4,
array = [1],
temp,
i,
element = document.querySelector('#a');
element.innerHTML += array.join(' ');
while (array.length < length) {
temp = [1];
for (i = 0; i < array.length - 1; i++) {
temp.push(array[i] + array[i + 1]);
}
temp.push(1);
array = temp;
element.innerHTML += '<br>' + array.join(' ');
}
<div id="a" style="text-align: center"></div>

add x number of every 10th element

I want to add number of every 10th element.
For example,
function myFunction() {
for (var i = 1; i <= 100; i++)
{
var d = i;
document.getElementById("demo").innerHTML += d+"<br/>";
}
}
Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
But, I want like this
1,2,3,4,5,6,7,8,9,10,16,17,18,19,20,21,22,23,24,25,31,32,33,34,35,36,37,38,39,40....
I want to add 5 after 10th number, add 10 after 20th number, add 15 after 30th number, add 20 after 40th number, add 25 after 50th number. I know this is simple. But, I couldn't get any result.
JsFiddle
You could take an offset and increment this value by five if the result of the index variable is dividable by ten.
var i,
offset = 0,
result = [];
for (i = 1; i <= 100; i++) {
result.push(i + offset);
if (i % 10 === 0) offset += 5;
}
console.log(result.join(' '));
You could use the modulo operator % to check if the current number (i) is a multiple of 10, then if it is, add 5 to i:
if (i % 10 === 0) {
i += 5;
}
Moreover, I recommend that you keep a string of all the numbers you want to append to your page, as querying and adding contents to the DOM each loop iteration is an expensive operation which can be avoided
See example below:
function myFunction() {
var resultStr = ""
for (var i = 1; i <= 100; i++) {
resultStr += i + "<br/>";
if (i % 10 === 0) {
i += 5;
}
}
document.getElementById("demo").innerHTML += resultStr;
}
myFunction();
<div id="demo"></div>
I used a counter to account for in increment on the 10th element, and am simply putting the results on the console. Obviously there are some that would simply just add 5, the counter option is just a design preference.
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
function myFunction(arr){
var counter = 0;
for(var i = 0; i<arr.length; i++){
if (i%10 ==0){
counter++;
}
arr[i] = arr[i]+(5*(counter-1));
}
console.log(arr);
};
myFunction(arr);
Do something like:
function myFunction() {
for (var i = 1; i <= 100; i++)
{
var j=Math.floor(i/10);
var x=5*j;
var d = x+i;
document.getElementById("demo").innerHTML += d+"<br/>";
}
}
Expanding on the performance issue presented by Nick Parsons
var resultStr = ""
for (var i = 1; i <= 100; i++) {
resultStr += i + "<br/>";
if (i % 10 === 0) {
i += 5;
}
}
document.getElementById("demo").innerHTML += resultStr;
innerHTML is just horribly slow.
Consider the following code that employs a document fragment and the vanilla .append() method
const fragment = document.createDocumentFragment();
for (var i = 1; i <= 100; i++)
{
if( i % 10 === 0 )
i += 5;
fragment.append( document.createTextNode( i ) );
fragment.append( document.createElement('BR') );
}
document.getElementById('demo').append( fragment );
From my testing, it's about 2000(!) times faster to use a document fragment.
Change your fucntion like that:
function myFunction() {
for (var i = 1; i <= 100; i++) {
var d = i;
if (i > 1 && i % 10 === 1) {
d = (i % 10) * 5 + i;
}
document.getElementById("demo").innerHTML += d + ",";
}
}

What is the difference in calculation between a code in C# and Javascript

I was looking for an answer for a question from Project Euler and I found one here
http://www.mathblog.dk/triangle-number-with-more-than-500-divisors/
int number = 0;
int i = 1;
while(NumberOfDivisors(number) < 500){
number += i;
i++;
}
private int NumberOfDivisors(int number) {
int nod = 0;
int sqrt = (int) Math.Sqrt(number);
for(int i = 1; i<= sqrt; i++){
if(number % i == 0){
nod += 2;
}
}
//Correction if the number is a perfect square
if (sqrt * sqrt == number) {
nod--;
}
return nod;
}
So I tried to implement the same solution in Javascript but it doesn't give me the same result.
var number = 0;
var i = 1;
while (numberOfDivisors(number) < 500) {
number += i;
i++;
}
console.log(number);
function numberOfDivisors(num) {
var nod = 0;
var sqr = Math.sqrt(num);
for (i = 1; i <= sqr; i++) {
if (num % i === 0) {
nod += 2;
}
}
if (sqr * sqr == num) {
nod--;
}
return nod;
}
I tested the other code in C# and it gives the right solution. I was wondering if I made a mistake or whether they work differently in some aspect I'm unaware of.
The problem is that you are testing non-triangle numbers because you forgot one important thing ... scope ...
for (i = 1; i <= sqr; i++) {
screws your (global) value of i ...
see in c# you have
for(int i = 1; i<= sqrt; i++){
^^^
give javascript the same courtesy and try
for (var i = 1; i <= sqr; i++) {
^^^
you should also get the square root as an integer, otherwise you'll be one off in most counts
var sqr = Math.floor(Math.sqrt(num));
i.e.
var number = 0;
var i = 1;
console.time('took');
while (numberOfDivisors(number) < 500) {
number += i;
i++;
}
console.timeEnd('took');
console.log(number);
function numberOfDivisors(num) {
var nod = 0;
var sqr = Math.floor(Math.sqrt(num));
for (var i = 1; i <= sqr; i++) {
if (num % i === 0) {
nod += 2;
}
}
if (sqr * sqr == num) {
nod--;
}
return nod;
}
(added some timing info for fun)

Find the sum of all the primes below two million using java script

I am trying this code
var sum = 0
for (i = 0; i < 2000000; i++) {
function checkIfPrime() {
for (factor = 2; factor < i; factor++) {
if (i % factor = 0) {
sum = sum;
}
else {
sum += factor;
}
}
}
}
document.write(sum);
I am getting this error:
Invalid left-hand side in assignment
Change if(i % factor = 0) to if( i % factor == 0) and remove the function checkIfPrime() inside the for loop.
var sum = 0
for (i = 0; i < 2000000; i++) {
for (factor = 2; factor < i; factor++) {
if (i % factor == 0) {
sum = sum;
}
else {
sum += factor;
}
}
}
document.write(sum);
The function inside the loop is pointless.
it looks like your code outputs wrong result, for example prime numbers below 6 are 2, 3 and 5, their sum is 10, your code outputs 14 in this case.
Here is another code which outputs sum of primes below max value:
var sieve = [], primes = [], sum = 0, max = 5;
for (var i = 2; i <= max; ++i) {
if (!sieve[i]) {
// i has not been marked -- it is prime
sum += i;
for (var j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
console.log(sum);
credit to How to find prime numbers between 0 - 100?
function sumPrimes(num) {
var sum = 0;
for (var i = 2; i < num; i++) {
if (isPrime(i)) {
sum += i;
console.log(sum);
}
}
return sum;
}
function isPrime(num) {
if (num <= 1) return false;
else if (num <= 3) return true;
else if (num % 2 == 0 || num % 3 == 0) return false;
var i = 5;
while (i * i <= num) {
if (num % i == 0 || num % (i + 2) == 0) return false;
i += 6;
}
return true
}
console.log(sumPrimes(2000000));
Well, I did with 250 otherwise my screen would have frozen. First of you have to single out the prime numbers after placing them inside an empty Array, which I called primeNumbers from 2 to whatever number you want. Then I create a function that would filter the prime numbers and then add them all with a reduce method inside of another variable called sum and return that variable.
var primeNumbers =[];
for(var i = 2; i < 250; i++){
primeNumbers.push(i);
}//for loop
function isPrime(value){
for(var x=2; x< value; x++){
if(value % x===0){
return false;
}
}//for loop
return true;
}//function isPrime to filter
var sum = primeNumbers.filter(isPrime).reduce(function(acc, val) {
return acc + val;
}, 0);
console.log(sum);
when you are using a variable inside the loop you need to declare them. You have two points in this case
i is not declared
factor is not declare
Your if (i % factor = 0) is wrong, as pointed by some people above.
Also, you never call the checkIfPrime() method. I don't why you created them. Also, I improved your checkIfPrime() method. Please call sumOfPrimes() method in the code below and it should work. You can modify it according to your need
function sumOfPrimes()
{
var sum =0;
for (var i = 0; i < 2000000; i++)
{
var temp = Math.sqrt(i);
for (var factor = 2; factor < temp; factor++)
{
if (i % factor === 0)
{
sum += factor;
}
}
}
console.log(sum);
}
Try changing this line if (i % factor = 0) {
to
if (i % factor == 0) {

Categories