Question:
How To Multiply Numbers In Java Using For Loop?
anonymous
2009-04-01 09:48:54 UTC
I'm looking to take a loop and have the starting point 1, then in a loop multiply that number by 2 up to 64 times.

The question is for that old rice thing, where the person puts 1 grain of rice on one square, but each time it gets doubled.
Four answers:
SedativeChunk
2009-04-01 09:58:54 UTC
If your trying to multiply the loop control variable by 2, set another variable equal to the value of the variable and multiply it by 2:



int currentNum;



for (int i = 1; i <= 64; i++)

{

currentNum = i;

currentNum = currentNum * 2;

}



Or are you looking for a nested loop where the nested loop multiplies the outer loop control variable by 2? Ex:

int outerNum;



For (int i = 1; i <= 1000; i++)

{

// Set outer loop

outerNum = i;



for (int x = 1; x <= 64; x++)

{

// Multiply outer loop control by 2

outerNum = outerNum * 2;

}

}



I'm really not sure what you are trying to do here. You need to be more specific with your problem. I hope those examples help with whatever your problem is.
deonejuan
2009-04-01 10:17:40 UTC
Yes, I know this legend. Attributed to Alexander the Great, among others...



You have to use double to get to square 64, this problem overflows type long.



public class RiceChessboard {



public static void main( String[] args ) {

double riceKerns = 1;

System.out.printf( "%2d %.0f%n", new Integer(1),riceKerns);

for (int i = 1; i < 64; i++) {

System.out.printf( "%2d %.0f%n", i+1,riceKerns *= 2);



}



}

}

// 64 -> 9,223,372,036,854,776,000

to show how big that is:

$ 1,000,000,000 -- a billion dollars would take just over 31 years to spend @ $1 per second
anonymous
2009-04-01 09:55:13 UTC
int num = 1;



for(int i = 0; i < 64; i++)

{

num *= 2;

}
Joy
2015-04-28 20:56:52 UTC
complex factor. query with google or bing. this will help!


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...