Numeric operators

Java Multithreading
Level 10 , Lesson 3
Available
Numeric operators - 1

"Hi, Amigo!"

"I want to tell you about numeric operators."

"Bilaabo already told me!"

"Really? Then I'll ask just a couple of questions."

"How do you increase a variable by 1? Give me as many options as possible."

"Easy."

Code
x++;
++x;
x = x + 1;
x += 1;

"That's right. And now what if you need to multiply the variable by two?"

"Done."

Code
x = x * 2;
x *= 2;
x = x + x;
x += x;
x = x << 1;
x <<= 1;

"How do you raise a variable to the ninth power?"

"This still doesn't require thinking."

Code
x = x*x*x*x*x*x*x*x*x;
x = x*x*x; (x3)
x = x*x*x; (x3*x3*x3 = x9)
x = Math.exp( 9 * Math.log(x)); // x9 == exp(ln(x9)) == exp(9*ln(x));

"The square root of a number?"

"Piece of cake."

Code
Math.sqrt(x)
x = Math.exp(0.5 * Math.log(x)); // x1/2 = exp(ln(x0.5)) == exp(0.5*ln(x));

"Sine of pi/2?"

Code
x = Math.sin(Math.PI/2);

"A random number between 0 and 1?"

Code
x = Math.random();

"A random number between 0 and 3?"

Code
x = Math.random() *3;

"A random number between 0 and 10?"

Code
x = Math.random() *10;

"A random number between -5 and 5?"

Code
x = Math.random() *10 - 5;

"A random number between -1 and 1?"

Code
x = Math.random() *2 - 1;

"A random number between 0 and 100?"

"I even have two solutions for you:"

Code
int x = (int) (Math.random() *100);
Random random = new Random();
int x = random.nextInt(100);

"Brilliant! I'm impressed. You have a splendid grasp of the topic."

Comments (1)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Andrei Level 41
7 June 2021
Damn, Amigo, I think you've been studying on the side as well !