Knowing that perfect squares are located at well-defined intervals:
- Q1 = 0 + 1 = 1
- Q2 = 1 + 3 = 4
- Q3 = 4 + 5 = 9
- Q4 = 9 + 7 = 16
- Q5 = 16 + 9 = 25
Simplifying:
- Q1 = 1
- Qn = Qn-1 + 2n - 1
We can print the sequence, without depending on sqrt
, what makes this the fastest way (only... it’s not always like this) to process such a sequence:
function QuadradoPerfeito(n) {
var out = '';
var x = 1;
for (var i = 3; ; i += 2)
for (var j = 0; j < i; j++) {
if (x > n) return out;
out += x + (j == 0 ? ' QUADRADO PERFEITO' : '') + '<br>';
x++;
}
}
document.body.innerHTML = QuadradoPerfeito(100);
But two nested ties... is not slower?
Despite having two nested loops, the total amount of calculations made is linear, because the output condition is on the variable x
, which is increased in every passage.
In addition, the browser is able to optimize these nested loops in such a way,
that even redoing the code with a single loop, the result is even slower,
however it is much easier to understand the logic.
There goes a simulation of what happens when calling the method with n=20
:
i=3:
j=0: x=1 // QUADRADO PERFEITO
j=1: x=2
j=2: x=3
i=5:
j=0: x=4 // QUADRADO PERFEITO
j=1: x=5
j=2: x=6
j=3: x=7
j=4: x=8
i=7:
j=0; x=9 // QUADRADO PERFEITO
j=1; x=10
j=2; x=11
j=3; x=12
j=4; x=13
j=5; x=14
j=6; x=15
i=9:
j=0; x=16 // QUADRADO PERFEITO
j=1; x=17
j=2; x=18
j=3; x=19
j=4; x=20
Single loop version, provided by @Bacco
Based on the comments on the amount of loops, @Bacco made a version that has exactly the same logic, but in a single loop.
But beware: this unique tie is no better in terms of performance than the double ties presented at the beginning of this answer! This version is to help people with less experience view logic.
function QuadradoPerfeito(n) {
var out = '';
var x = 1;
var s = 1;
var i;
for ( i = 1; i <= n ; i++ ) {
out += i;
if ( i == x ) {
out += ' QUADRADO PERFEITO';
x = i + (s += 2 );
}
out += ' <br>';
}
return out;
}
document.body.innerHTML = QuadradoPerfeito(100);
As the question gives no further details, it follows a possibility:
function QuadradoPerfeito() { document.write( "1 2 3 4 QUADRADO PERFEITO 5 6 7 8 9 QUADRADO PERFEITO 10 11 12 13 14 15 16 QUADRADO PERFEITO 17 18 19 20 21 22 23 24 25 QUADRADO PERFEITO 26 27 28 29 30 31 32 33 34 35 36 QUADRADO PERFEITO 37 38 39 40 41 42 43 44 45 46 47 48 49 QUADRADO PERFEITO 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 QUADRADO PERFEITO 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 QUADRADO PERFEITO 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 QUADRADO PERFEITO" ) }
:P– Bacco
I don’t understand what you mean by "perfect square":P
– Ricardo
@Ricardo http://pt.wikipedia.org/wiki/Quadrado_perfeito
– Bacco