This program outputs a table.
- Column 1 – number (1 to 100)
- Column 2 – Square root of the number
- For this we use built in math function – Math.Sqrt(i)
- Column 3 – Square
- i*i
- Column 4 – Cube of the number
- i*i*i
- Column 5 – Binary of the number
- toString(2)
- Column 6 – Complement of the number
- ~i
How to find the complement of a number.
To make the code short, we use javascript in-built option of using ~ to find the complement of the number.
First of all, you need to realize that ~ is the bitwise flip operator, which is not the same as the negate operator -. ~ does only do the bitwise flipping, but the negate operator – does bitwise flipping and add one (for integers).
As you’ve explained, if yo want to go from a postive number n to -n using the two complement method you bitwise flip/not n and add 1. ~n is just the bit-wise not meaning that ~n=-n-1.
For instance:
5 = 0000 0101
Flipped (~5) = 1111 1010
So, which number does 1111 1010 represent? Since the first digit is a 1 we know it’s a negative value. To find which value, do
-(flip(1111 1010) + 1) =
-(0000 0101 + 1)
-(0000 0110) =
-6
<HTML>
<HEAD>
<TITLE> squares, roots, cubes and complements of integers between 1 and 100. </TITLE>
</HEAD>
<BODY>
<form>
<h1>Squares, Roots, Cubes and Complements of Integers between 1 and 100. </h1>
<script language ="javascript">
{
document.write("<table border =1 ><tr><td>Number</td><td>Square Root</td><td>Squares</td><td>Cubes</td><td>Binary</td><td>Complements</td></tr>");
for(i=1;i<=100;i++)
{
document.write("<tr><td> "+ i + "</td><td> " + Math.sqrt(i) + "</td><td> "+i*i +"</td><td>"+ i*i*i+"</td><td>"+ i.toString(2)+"</td><td>"+ ~i+"</td></tr>");
}
}
</script>
</form>
</BODY>
</HTML>