The fastest way to square a number is to multiply it by itself.
Why is
Math.powso slow?
It's really not, but it is performing exponentiation instead of simple multiplication.
and why does it cope badly with > 1 and even worse with < -1 numbers
First, because it does the math. From the Javadoc it also contains tests for many corner cases. Finally, I would not rely too much on your micro-benchmark.
Answer from Elliott Frisch on Stack OverflowVideos
The fastest way to square a number is to multiply it by itself.
Why is
Math.powso slow?
It's really not, but it is performing exponentiation instead of simple multiplication.
and why does it cope badly with > 1 and even worse with < -1 numbers
First, because it does the math. From the Javadoc it also contains tests for many corner cases. Finally, I would not rely too much on your micro-benchmark.
Squaring by multipling with self is the fastest. Because that approch can be directly translated into simple, non-branching bytecode (and thus, indirectly, machine code).
Math.pow() is a quite complex function that comes with various guarantees for edge cases. And it need to be called instead of being inlined.
Yes. Call the method println from System.out (not String.out which doesn't exist), you don't assign a value to it. And you multiply the int you parsed.
String.out.println = mataintal * mataintal;
should be
System.out.println(nr * nr);
this makes no sense>
String.out.println = mataintal * mataintal;
you print using
System.out.println();
on the other hand, mataintal is a String, you need instead nr which is the result of parsing that string into an integer
your final line must be like:
System.out.println(nr * nr);