Simple explanation of checking prime numbers - javascript

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.

Related

How to find square of n with a for loop 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

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

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!

Algorithm: Next Greater Element I (from leetcode)

can someone please tell me what I'm missing in solving this algorithm? One problem I have is that my first if statement inside the nested loop is not evaluating, but I don't know why it wouldn't evaluate.
Here is the description of the problem:
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
link to original description
And here is my code so far:
var nums1 = [4,1,2];
var nums2 = [1,3,4,2];
var nextGreaterElement = function(findNums, nums) {
var holder = [];
for (var i = 0; i < findNums.length; i++) {
//loop through the 2nd array starting at the index of the first loop's current item.
for (var j = nums.indexOf(findNums[i]); i < nums.length - j; i++) {
if (nums[j+1] > nums[j]) {
holder.push(nums[j+1]);
break;
}
if (nums[nums.length]) {
holder.push(-1);
}
}
}
return holder;
};
nextGreaterElement(nums1, nums2)
Thanks for any help.
Problem: Updating variant i, but not variant j in inner loop (j-loop)
Missing: Debugging Effort
Problem Description
Theoretically, your code design should compare each value in nums1 to related parts of nums2. So, it would turn to a outer for-loop to loop on nums1 and an inner for-loop to loop related parts of nums2 for each iteration of the outer for-loop.
In your code, variant i is the index pointer for findNums (i.e. nums1) while variant j is the index pointer for nums (i.e. nums2). Variant i is always updating in both inner for-loop and outer for-loop while variant j is set once for every iteration of outer for-loop. This contradict to what you are suppose to do.
Debugging (Your Missing Work)
Find a piece of paper and a pen. Sit down, dry run the program and keep recording related info (variant i, variant j, findNums[i], nums[j], ...), you could figure out why your code is not working.
Possible Solution
var nextGreaterElement = function(findNums, nums) {
var holder = [];
for (var i = 0; i < findNums.length; i++) {
var hasNextGreaterElement = false;
// try to serach for next greater element
for (var j = nums.indexOf(findNums[i])+1; j < nums.length; j++) {
// handle case for next greater element is found
if (nums[j] > findNums[i]) {
holder.push(nums[j]);
hasNextGreaterElement = true;
break;
}
}
// handle case for next greater element is not found
if (!hasNextGreaterElement) {
holder.push(-1);
}
}
return holder;
};
var findNums=[4,1,2];
var nums=[1,3,4,2];
console.log(nextGreaterElement(findNums, nums));
You need to sort the array you are looking in to make it easier to find the number. If the array get big you might want a search algorithm to find the index in the array faster. With the array that is going to be looked in sorted you can grab the next number as the number that is one larger and check to see if you are at the end of the array. If you don't do this check the function will error when you can't find the number or when there is no number larger. Finally your second if statement didn't make sense. So I am checking to make sure that we are at the end of the array before outputting the -1 in the array.
var nextGreaterElement = function(findNums, nums) {
var holder = [];
//Should sort the array to make sure you get the next largest number
nums = nums.sort();
for (var i = 0; i < findNums.length; i++) {
//loop through the 2nd array starting at the index of the first loop's current item.
//for (var j = nums.indexOf(findNums[i]); i < nums.length - j; i++) {
for(var j = 0; j < nums.length; j++){
//check for value in array and make sure the value is not at the end
if (findNums[i] == nums[j] && j != nums.length - 1) {
holder.push(nums[j+1]);
break;
}
//check for the last element in array if so output -1
if (j == nums.length - 1) {
holder.push(-1);
}
}
}
return holder;
};

Categories

Resources