How to find square of n with a for loop javascript - javascript

Can someone walk me through the following code:
function square(n) {
let result = 0;
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
result += 1;
}
}
return result;
}
//
example:
console.log(square(5)) // 25
How does this for loop work in creating a square of an n number? I don't know where to start in approaching how this works.

The square of a number can be visualized as the number of squares in a grid. 5x5, for example, is 5 wide by 5 tall:
You can think of the nested loop in your code
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
result += 1;
}
}
emulating movement along the grid.
When i is 1, it's going along the first row. When j is 1, that corresponds to the first column. That corresponds to the first square. Next iteration corresponds to the first row, second column - etc, until i <= n is no longer fulfilled, at the end of the row. The next row then iterates n times, and so on.
You'll see that the number of total iterations (where result += 1 runs) is equivalent to n * n, as the nested loop implements.

In short, the inner(j) loop runs 5 times for every iteration of the outer(i) loop..
Basically,
for each i = 1, j runs 5 times
for i = 2, j runs 5 times //total 10 times
for i = 3, j runs 5 times //total 15 times
for i = 4, j runs 5 times //total 20 times
for i = 5, j runs 5 times //total 25 times
So the result gets incremented 25 times, and hence the answer is 25

Related

Increment a variable by 3 in a loop that increments by 1

I want to create a loop where the "i" variable is incrementing by one (i++), and I want to add another variable "j" in the loop that increment not by one but 3 per 3 (so j+=3, and then the output looks like 0, 3, 6, 9, 12...).
I have tried so many thing, but here is my code that looks logic :
let j;
for (let i = 0; i < 24; i++) {
j = i += 3;
console.log(j); //It increments by 4, WTF ??
console.log(i); //Exactly the same whereas i should increments per 1
}
I also tried to create a variable "k" that is equal to "i" to leave "i" alone, but still doesn't work.
Thank you so much for your help guys :)
PS : Once solved, do you know how to make the variable j starts by 0 please ?
let j=0;
for (let i = 0; i < 24; i++) {
j+=3
console.log(j); //starts at 3, because in the first line of the function we say j = 0 + 3, so j=3, then once it loops again it gets +3 again, so it's 6 and so on.
console.log(i); //just increments by 1 each loop
Try this, is this what you were trying to achieve?
Like this - you can use comma separators in the initiator and loop statements in the for statement
for (let i = 0, j = 1; i < 24; i++, j += 3) {
console.log("i",i,"j",j);
}

Iterating using a quadratic sequence in Javascript

I have a quadratic sequence in which I need to use to loop over, however, I am not sure how to execute this kind of logic... I want to use the quadratic sequence to count up to a given number <= n. The problem is that I have to give my quadratic sequence for loop some number to count and iterate up to as well... I know it's possible to iterate by 2s, 3s, 4s, etc. by doing things like i += 2, is it possible to use a quadratic expression as well? Is there a method using Javascript in which will allow me to iterate through quadratic sequences? I hope this is clear, thanks!
Here's my code:
The quadratic sequence is the sequence being console logged.
The first 14 terms are: 1,3,6,10,15,21,28,36,45,55,66,78,91,105
for (let i = 1; i <= 14; i++) {
let a = i;
let nthTerm = a - 1;
let b = 1 / 2;
let quadraticSequence = b * a ** 2 + b * a;
console.log(`${nthTerm} ${quadraticSequence}`);
const num = 93;
// use quadratic sequence to count up to a number <= 93;
for (i = 0; i <= num; i++quadraticSequence) {
console.log(i);
}
}
The result should console.log a count 0 > 105. I know the second for loop is not correct, but I'm not quite sure how to approach a proper attempt.
So instead of counting like, 1,2,3,4,5,6,7,8,9... It should count 1,3,6,10,15,21,28,36,45,55... Ultimately, I am trying to count up to a given number <= n (i.e. 93) through the quadratic sequence instead of the usually, 1,2,3,4,5, sequence.
let num = 93;
for (let i = 1, j = 2; i < 100; i += j, j += 1) {
console.log(i);
for (let k = 0; k <= num; k += i) {
console.log(k);
}
}
This will produce the sequence 1, 3, 6, 10, 15, 21, 28, 36, ... and then use each of them in a seperate for loop as step size.
An alternative interpretation would be using the 0th element in the quadratic series as the first step size and the next element as the next step size, etc.
for (let i = 1, j = 2, k = 0; k < 1000; k += i, i += j, j += 1) {
console.log(`Current, step: ${k}, ${i}`);
}
This should do that

How to iterate over a JSON object in chunks of 3?

So i have a json object that is being served by nodejs.
I'm wanting to make articles in rows of 3, then div's in rows of 3 below the articles (that contain the information for the articles.
for (var infoset in jsonObj){
createArtRow(jsonObj[infoset][info]);
createDivRow(jsonObj[infoset][info]);
// creates an article, then a div one at a time
}
I'm having issues, because i'm unsure how to join the for loop iterating over the object (only 3 at a time).
for (var infoset in jsonObj){
for (var i = 0; i < 3; i ++) {
createArtRow(jsonObj[infoset][info]);
}
for (var i = 0; i < 3; i ++){
createDivRow(jsonObj[infoset][info]);
}
}
// ideally creates 3 articles, then 3 divs at a time.
I hope that makes sense.
Use a loop that increments by 3 instead of 1.
for (var i = 0; i < jsonObj.length; i += 3) {
// here you can use jsonObj[i], jsonObj[i+1], and jsonObj[i+2] to create a row
}
You could use modulus funcion, which i think is a cleaner more readable approach:
let i =0
for (var infoset in jsonObj){
If (i % 3 == 0 ){
createArtRow(jsonObj[infoset][info]);
}
createDivRow(jsonObj[infoset][info]);
i++;
}
Modulus (%) function works by deviding 'i' by the number after the % sign.
If the remainder is 0 (so exactly dividable by 3), it will be true and execute the code.

Simple explanation of checking prime numbers

I would like someone to explain me, how this code work? Because I cannot understand exactly.
This code write in console all prime numbers between 2 and n.
let n = 10;
nextPrime:
for (let i = 2; i <= n; i++) {
for (let j = 2; j < i; j++) {
if (i % j == 0) continue nextPrime;
}
console.log(i);
}
Prime number is a number that can be divided by 1 and itself and has no other dividers.
This code loops over <2...n) range to check if the number can be divided by it (i % j == 0). If it can be divided by that number, it means that i is not a prime number, so we continue nextPrime, which means ending current iteration and proceeding to the next one. If we never run continue for particular j, it means it's a prime number.
Since you asked about nested loops, I'll try to explain why they are like that here. For simplicity, let's assume we need all prime numbers up to 5 instead of 10. Your loop is as follows:
for (let i = 2; i <= n; i++) {
for (let j = 2; j < i; j++) {
That means that we're gonna check the following pairs of i and j, in order:
i = 3, j = 2
i = 4, j = 2
i = 4, j = 3
i = 5, j = 2
i = 5, j = 3
i = 5, j = 4
Here the function of inner for loop is to check whether the current value of i is prime or not.
Now how inner loop will do this ? See the basic definition if a number is divisible by only 1 and itself then it is prime no. But here the value of "j" is starting from 2 and going upto less than that number. So if "i" is divisible from any other no. then condition (i%j==0) will become true and code written inside that block will be executed.
And the code written inside it is continue nextPrime which will redirect the execution of program again to where nextPrime keyword is written. So the console.log(i) statement will not execute for that value of i.
And if condition not becomes true (means when it is prime) then it execute the last line which will print that no.

What is the Big O for the following functions:

I need help with the following problems on determining what the Big O is of each function.
For problem one, I've tried O(log(n)) and O(n). I figured the function was linear or in other words, for N elements we will require N iterations.
For problem two, I've tried O(n^2). I figured for this kind of order, the worst case time (iterations) is the square of the number of inputs. The time grows exponentially related to the number of inputs.
For problem three, I've tried O(n^2) and O(1).
Problem One:
function foo(array){
let sum = 0;
let product = 1;
for (let i = 0; i < array.length; i++){
sum += array[i]
}
for(let i = 0; i < array.length; i++){
product *= array[i];
}
consle.log(sum + ", " + product);
}
Problem Two:
function printUnorderedParis(array){
for(let i = 0; i < array.length; i++){
for(let j = i + j; j < array.length; j++){
console.log(array[i] + ", " + array[j]);
}
}
}
Problem Three:
function printUnorderedPairs(arrayA, arrayB){
for(let i = 0; i < arrayA.length; i++){
for(let j = 0; i < arrayB.length; j++){
for(let k = 0; k < 100000; k++){
console.log(arrayA[i] + ", " + arrayB[j]);
}
}
}
}
I expected my initial thoughts to be right, but maybe I'm having a hard time grasping Big O.
You're correct that it's O(n). You have two loops, they each perform array.length iterations. You could even combine them into a single loop to make it more obvious.
for (let i = 0; i < array.length; i++) {
sum += array[i];
product *= array[i];
}
You're correct, it's O(n^2). The nested loops perform array.length * array.length iterations.
EDIT -- see my comment above asking whether this problem is copied correctly.
This is also O(n^2). The third level of nested loop doesn't change the complexity, because it performs a fixed number of iterations. Since this doesn't depend on the size of the input, it's treated as a constant. So as far as Big-O is concerned, this is equivalent to Problem 2.
Well, you kind of answered your questions, but here we go:
In the first problem, you have two for loops, each of them iterating over the entire array. For a general array of size n, you'll have O(2n) or simply O(n) since we can let go of constants. There isn't any reasons this would be O(log(n)).
For the second one, I think there is a mistake. The statement j = i + j is not valid, and you'll get Uncaught ReferenceError: j is not defined. However, let's say the statement is actually let j = i. Then, we have:
i, iterating over the entire array, starting from the first element and going all the way to the last one
j, starting from i and going all the way to the last element
With this information, we know that for i = 0, j will iterate from 0 to n (n being the array's length), so n steps. For i=1, j will go from 1 to n, so n-1 steps. Generalizing, we are going to have a sum: n + (n - 1) + (n - 2) + ... + 1 + 0 = n * (n + 1) / 2 = 1/2 * (n^2 + n). So, the complexity is O(1/2 * (n^2 + n) = O(n^2 + n) = O(n). So you were correct.
For the third problem, the answer is O(n^2) and not O(1). The reasoning is very close to the one I made for the second one. Basically, the inner k will be executed 100000 times for every j iteration, but the number of iteration does not depend of n (the size of the array).
It's easy to see that:
for i = 0, j will go from 0 to n (last value for which j body will be executed being j = n - 1).
for j = 0, we will to 100k iterations
for j = 1, another 100k iterations
...
for j = n - 1, another 100k iterations
The entire j loop will make n * 100000 = 100000n iterations.
For i = 1, the same behaviour:
for j = 0, we will to 100k iterations
for j = 1, another 100k iterations
...
for j = n - 1, another 100k iterations,
getting another 100000n iterations.
In the end, we end up with 100000n + 100000n + ... + 100000n (n times) = sum(i = 0, n, 100000n) = n * 100000n = 100000 * n^2. So, the big O is O(100000 * n^2) = O(n^2).
Cheers!

Categories

Resources