0

I want to print the root of all numbers to 9999. How do I tell the program to skip the numbers that don't have a round root? Here's the code

let i=1;

for (i===1;i>=1 && i <10000;i++){
    let b = Math.sqrt(i);
    console.log(`${i} = ${b}`);
}
  • btw: i wonder what's a reason to make the `i===1` check in the first part of your for-clause; is that a typescript thing? since this could be just omitted in regular js oO – garglblarg Nov 01 '16 at 14:15
  • In fact, `i===1` there is invalid in JS. – Cerbrus Nov 01 '16 at 14:16
  • In both languages when you write only two == Example: Let a = 5; Let b = "5"; if (a==b).... It will consider it as true , because it turns a in a string of 5. When you have === , 5 won't be equal to "5", because the one is a number and the other is a string type. Shortly === checks not only the value, bit the type too –  Nov 01 '16 at 15:30
  • 1
    ok to clarify, i didn't ask about the === but _why_ you would write a condition in the place where usually the initialization of the indexer takes place. because the value of the condition isn't used: in fact you could just write `false` instead of `i===1` and it still works. – garglblarg Nov 01 '16 at 15:46
  • Just 2 cents of mine. This is not an exact duplicate plus the OP is totally a newbie. – Praveen Kumar Purushothaman Nov 01 '16 at 22:18

2 Answers2

2

You can check if both the int value and the original value are same.

let i=1;

for (i=1;i>=1 && i <10000;i++){
    let b = Math.sqrt(i);
    if (Math.trunc(b) == b)
        console.log(`${i} = ${b}`);
}

Instead of Math.trunc(b), you can use either of the following:

  • Math.round(b)
  • Math.floor(b)
  • Math.ceil(b)
  • parseInt(b, 10)
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

You don't need to iterate and test every number up to 10000. You can directly compute powers of two:

var count = 0, i = 0;
while (count < 10000) {
  i++;
  var b = i * i;
  console.log(`${i} = ${b}`);
  count = b;
}

Or as mentioned in comments you can do it elegantly with for-loop:

for (let i = 1; i*i < 10000; i++) {
  console.log(`${i*i} = ${i}`);
}
madox2
  • 49,493
  • 17
  • 99
  • 99
  • 1
    Shorter: `for (let i = 1; i * i < 10000; i++){ console.log(\`${i*i} = ${i}\`);}` – Cerbrus Nov 01 '16 at 14:12
  • 1
    Also, your `while` condition isn't right. you're only getting up to `31`, while the last result should be `99` – Cerbrus Nov 01 '16 at 14:24
  • I can't see the point in that code. I wan't to print the root of the numbers. –  Nov 01 '16 at 15:34
  • @Xcd: You want all possible values, for which the root of said value is a integer. So why not iterate over said integers? That's way faster than iterating over every possible value, taking the root of it, and checking if it's an integer. – Cerbrus Nov 03 '16 at 07:58