Win a copy of Head First Android this week in the Android forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Paul Clapham
• Ron McLeod
• Tim Cooke
• Junilu Lacar
Sheriffs:
• Rob Spoor
• Devaka Cooray
• Jeanne Boyarsky
Saloon Keepers:
• Jesse Silverman
• Stephan van Hulst
• Tim Moores
• Carey Brown
• Tim Holloway
Bartenders:
• Jj Roberts
• Al Hobbs
• Piet Souris

# For loops equation (can't figure out)

Greenhorn
Posts: 1
• Number of slices to send:
Optional 'thank-you' note:
I'm fairly new to java and I'm having trouble figuring out how to do this equation using "for loops" anyone on here help/post solution?

A chess board has 64 squares. Suppose you were to put one cent on the first square, then 2 cents on the second, then 4 cents on the third, then 8 cents on the fourth , until all the squares were covered.
Using a "for loop", create a program to answer the following questions

q1 What would be the amount placed on the 64th square ?
q2 What would be the total amount placed on the board ?

Greenhorn
Posts: 7
• Number of slices to send:
Optional 'thank-you' note:
You don't really need to imagine a chess board for this. It's just used for the arbitrary limit of 64 tiles. You basically need to find the function defined by the sequence f(1) = 1, f(2) = 2, f(3) = 4, f(4) = 8, ... and then use that function to find f(x = 64) for the first question and then to find f(1) + f(2) + ... + f(63) + f(64) for the second question.

Marshal
Posts: 74354
334
• Number of slices to send:
Optional 'thank-you' note:
Welcome to the Ranch

What your teacher has forgotten is that you cannot fit such large numbers into an int nor into a long. You will have to use BigInteger. It has a pow(int) method which you will find useful. Don't writeWriteThat has to do with BigInteger being immutable. AB is correct that you can do the exercise without a loop.

Bartender
Posts: 732
10
• Number of slices to send:
Optional 'thank-you' note:
You do not need to use pow() to solve this. Each square contains twice the previous value.

The first square contains f(1) =2^0=1, the second contains f(2) = 2^1=2 = 2*f(1), the nth contains f(n) = 2^(n-1) = 2 * f(n-1)  so the 64th square contains 2^63.

As Campbell Ritchie pointed out, this is larger than will fit in an int or long (The maximum ling is 2^63 - 1).

 You showed up just in time for the waffles! And this tiny ad: Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton