Why this code printing wrong prime numbers? - javascript

"I think problem is in for loop. Because i have used same "j" to iteration in both function's loop."
I wanted to print all prime number from 1-100.
I think all code is good. But it kept showing output other than prime numbers.
I can't find answers myself . And no other places has written answer. Please help me out here. I want to understand this problem.
var n = 100;
var prime1 = new Array();
//producing prime number upto 97
function primeNumber() {
for (j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
primeNumber();
console.log(prime1);
function countRemainder(n) {
var count = 0;
for (j = 1; j <= n; j++) {
if (n % j == 0) {
count++;
}
}
return count;
}

The problem was indeed happening because you were using the same variable in both for loops.
When you declare a variable like j = 0; and not like var j = 0; the variable will be added to global scope (instead of the scope you are in, so every other scope can see and alter that variable).
If your script is running in strict mode, then this will throw an error, instead of adding the variable to the global scope.
So just add var before each j declaration.
var n = 100;
var prime1 = new Array();
//producing prime number upto 97
function primeNumber() {
for (var j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
primeNumber();
console.log(prime1);
function countRemainder(n) {
var count = 0;
for (var j = 1; j <= n; j++) {
if (n % j == 0) {
count++;
}
}
return count;
}

Use "let" to declare "j" correctly.
function primeNumber() {
for (let j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}

Try this
var n = 100;
var prime1 = new Array();
//producing prime number upto 97
function primeNumber() {
for (var j = 1; j <= n; j++) {
if (countRemainder(j) == 2) {
prime1.push(j);
}
}
}
primeNumber();
console.log(prime1);
function countRemainder(n) {
var count = 0;
for (var j = 1; j <= n; j++) {
if (n % j == 0) {
count++;
}
}
return count;
}

Related

JS - Convert nested forloops into single loop

I need to convert this nested loop into a single loop.
This is the loop with the scenario:
First incrementer is i which starts from 0 and should run till 10
Second incrementer is j which starts from where i left off + 1 and runs till 10
.
.
My Nested Loop
for (var i = 0; i < 10; i++) {
for (var j = i + 1; j < 10; j++) {
if (some_condition) {
do_sth()
}
}
}
My Attempt at conversion
var i = 0;
while (i < 10){
var j = i + 1;
if (j < 10) {
if (some_condition) {
do_sth()
}
j++;
}
i++;
}
Unfortunately, my attempt doesn't produce the expected results.
The second snippet does not give the output which the first snippet delivers.
Can anyone please suggest me what my mistake is or provide me a better solution to achieve my target?
Thanks!
Not sure it improves readability complexity, but the following should produce the same.
var i = 0, j = 1;
while (i < 9) {
console.log(i, j);
j += 1;
if (j >= 10) {i += 1; j = i + 1}
}
You need to update i inside else statement or use continue. And declare j outside of the while body.
But keep in mind that this neither change "the order of complexity" nor "optimise" your code.
var i = 0;
var j = 1;
while (i < 10) {
if (j < 10) {
if (true) {
console.log(i, j)
}
j++;
} else {
i++;
j = i + 1;
}
}
You could adjust the loop lenght of i and check if j is greater or equal than 9, then increment i and start with fresh j.
var i = 0,
j = 1;
while (i < 9) {
console.log(i, j);
// do you stuff
if (j >= 9) j = ++i;
j++;
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

misprinted number in prime function

function primeSieve() {
for(i = 0; i <= 100; i++){
let flag = true
for(let j = 2; j < i/2; j++){
if(i % j === 0){
flag = false
}
}
if(flag){
console.log(i)
}
}
}
primeSieve();
Hi,
I'm studying some algos and ran into a prime sieve problem. I'm trying to print all prime numbers between 0 and 100 and it's working for the most part. However, i realized that 4 slipped in somehow and i can't figure out why for the life of me. Wondering if i can get a few pairs of eyes and see how 4 ended up being logged to the console and why that's the case.
thank you!
Your condition in the inner loop:
for (let j = 2; j < i / 2; j++) {
is
j < i / 2
This means that when i is 4, once j gets to 2 (or, since j is always initialized to 2, before the first iteration), the loop breaks. So, without any iterations, there's never any chance for an i of 4 to get to flag = false.
Change to
for (let j = 2; j <= i / 2; j++) {
Also, per wikipedia:
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
So you should probably start i at 2, not 0.
Also, just like your let j, it would be good to declare i with let as well so as not to implicitly pollute the global scope:
function primeSieve() {
for (let i = 2; i <= 100; i++) {
let flag = true
for (let j = 2; j <= i / 2; j++) {
if (i % j === 0) {
flag = false
}
}
if (flag) {
console.log(i)
}
}
}
primeSieve();
Beside the including the value for j to check with j <= i / 2, you could omit the use of a flag and use continue with a label for the outer loop.
function primeSieve() {
outer: for (var i = 2; i <= 100; i++) {
for (var j = 2; j <= i / 2; j++) {
if (i % j === 0) {
continue outer;
}
}
console.log(i);
}
}
primeSieve();

print prime nos upto 100 in javascript

<!DOCTYPE HTML>
<html>
<head>
<script>
var i, j, k = 1;
for (i = 3; i < 100; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
k = 0;
break
}
}
}
if (k == 1) {
alert(i);
}
</script>
</head>
<body>
</body>
</html>
I am trying to print prime nos in js from 2 to 100.However the code is not producing the desired result.Please help.Thanks in advance.
First you only need to check till j <= (i/2) in your for loop.
also your if(k==1) need to be inside the outer for loop
var i, j;
for (i = 3; i < 100; i++) {
var k = 1;
for (j = 2; j <= i / 2; j++) {
if (i % j == 0) {
prime = false;
k = 0;
break;
}
}
if (k == 1) {
console.log(i);
}
}

There's a bug in my code

My code isn't working . I'm trying to figure out what the bug is . Can someone help ? ! It's a function that is supposed to return an array of the first n triangular numbers.
For example, listTriangularNumbers(5) returns [1,3,6,10,15].
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
Your initial initialization of j is wrong, it's starting at i so it's going too high. Also switched the operators around to make sure the conditions work.
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; i++) {
num = i;
for (j = i-1; j >= 1; j--) {
num = num + j;
}
array.push(num);
}
return array;
}
You can try below code to get help:
a = listTriangularNumbers(8);
console.log(a);
function listTriangularNumbers(n) {
var num;
var array = [0];
for (i = 1; i <= n; i++) {
num = 0;
for (j = 1; j <= i; j++) {
num = num + j;
}
array.push(num);
}
return array;
}
You actually don't need 2 for-loops to do this operation. A single for-loop would suffice.
function listTriangularNumbers(n) {
// Initialize result array with first element already inserted
var result = [1];
// Starting the loop from i=2, we sum the value of i
// with the last inserted element in the array.
// Then we push the result in the array
for (i = 2; i <= n; i++) {
result.push(result[result.length - 1] + i);
}
// Return the result
return result;
}
console.log(listTriangularNumbers(5));
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i-1; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
var print=listTriangularNumbers(5);
console.log(print);

Javascript and for loops issue

Is something wrong with my code? I was expecting my code:
years=new Array();
for (i = 0; i < 5; ++i) {
for (j = 1; j < 13; ++j) {
player.push(Math.round( nestedData[i].value[j] ))
}
years.push(player)
}
console.log(years)
to print something like:
[array[12],array[12],array[12],array[12]]
but the result that i get is:
[array[60],array[60],array[60],array[60]]
Create a new player array inside the first for loop. The problem with your code is that the values were being pushed into the same array instance.
var years = [];
for (i = 0; i < 5; ++i) {
var player = [];
for (j = 1; j < 13; ++j) {
player.push(Math.round( nestedData[i].value[j] ))
}
years.push(player)
}
console.log(years)
As an addition to the correct answer already, please use var to declare your variables:
for (var i=0; i < 5; ++i) {
var player = [];
for (var j = 1; j < 13; ++j) {
...
Otherwise, it will use i as a global variable, which could end poorly if you have two functions looping at the same time, e.g.:
function loopone() {
//wouldn't expect this to be an infinite loop eh?
for (i=0; i < 100; i++) {
looptwo();
}
}
function looptwo() {
for (i=0; i < 10; i++) {
}
}

Categories