How do you calculate a (base * power) sans math.pow?

I've been tasked with trying to figure out how to do an exponent question without using the math.pow(3,2) method. How would I do that?
[142 byte] By [Shadowplaya] at [2007-11-26 18:50:29]
# 1

If the exponent is a nonnegative integer, just multiply in a loop, just like you did on paper when you first learned about exponents before you were taught the concepts of negative and fractional exponents.

For the general case, I don't nkow. I'm not enough of a math-head, but I would suppose there's an algorithm or approximation formula out there.

jverda at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 2
Yeah it's a non negative number but I don't understand how a loop would complete this.
Shadowplaya at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 3

> I've been tasked with trying to figure out how to do

> an exponent question without using the math.pow(3,2)

> method. How would I do that?

Are we talking about integers? Like jverd suggested, use a for loop to calculate the product. And if the (integer) power value is negative just return 1/product.

prometheuzza at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 4

> Yeah it's a non negative number but I don't

> understand how a loop would complete this.

Say you want to find the value of 10^5, you just do:

int product = 1;

product *= 10; // this is the same as product = product * 10

product *= 10;

product *= 10;

product *= 10;

product *= 10;

Use a for statement for this:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html

prometheuzza at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 5
do you mean like a for loop? wouldn't that just multiply the base times the power?for(base; base > 0; base *= product)?
Shadowplaya at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 6
> do you mean like a for loop? wouldn't that just> multiply the base times the power?> > for(base; base > 0; base *= product)?Why don't you try? See the link to the tutorial I posted? Try reading that as well.
prometheuzza at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 7
Sorry about that...I thought that might have been a sig
Shadowplaya at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 8
And if you really want to an impression,use a recursive method. http://danzig.jct.ac.il/java_class/recursion.htmlkari-matti
kari-mattia at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 9
> Sorry about that...I thought that might have been a> sigAh, I see. No problem.; )
prometheuzza at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 10
Somehow I've got to increment the product into a total correct?so base = 6power = 1product = 6total = total + product
Shadowplaya at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 11

You do it using recursion:

public double pow(double b, double e)

{

if (e < 0){ b = 1.0/b; e*=-1;}

if (e == 0) return 1;

return b * pow (b, e - 1);

}

Carlemagnea at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 12
I can't use pow, pow is a math method.
Shadowplaya at 2007-7-9 6:24:30 > top of Java-index,Java Essentials,Java Programming...
# 13

> I can't use pow, pow is a math method.

public static double iCantUsePow(double b, double e)

{

if (e < 0){ b = 1.0/b; e*=-1;}

if (e == 0) return 1;

return b * iCantUsePow (b, e - 1);

}

Done.

Carlemagnea at 2007-7-9 6:24:31 > top of Java-index,Java Essentials,Java Programming...
# 14
> You do it using recursion:> > ...Carlemagne, making the OP's homework will not help him much. You can better give some hints so s/he finds the solution on his/her own, IMHO.
prometheuzza at 2007-7-9 6:24:31 > top of Java-index,Java Essentials,Java Programming...
# 15

> Somehow I've got to increment the product into a

> total correct?

>

> so base = 6

>

> power = 1

>

> product = 6

>

> total = total + product

So, if someone tells you to compute 2 to the 5th power on paper, you'd write down 2 + 2 + 2 + 2 + 2?

You do it in a loop by doing the same thing N times.

jverda at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 16

> You do it using recursion:

No, that's not an appropriate approach for him at this point. He should do it the easy way first, to make sure he understands the basic concepts that are being taught. After that, if he wants to keep exploring and learning, he could try to adapt it to a recursive solution.

jverda at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 17
It doesn't matter, I don't understand what he's writing anyway :(
Shadowplaya at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 18

> Somehow I've got to increment the product into a

> total correct?

>

> so base = 6

>

> power = 1

>

> product = 6

>

> total = total + product

Ok this is how you do it:

- set total to 1,

- loop a power-number of times using the for-statement,

- each time in the loop multiply total times base.

I advice you not to use the code which was posted by Carlemagne. It uses recursion, which is beyond your current scope, and is not written very well. It will crash when you use irrational numbers for e.

prometheuzza at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 19
> It doesn't matter, I don't understand what he's> writing anyway :(Good.; )
prometheuzza at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 20

Man this is frustrating

total = 1

for(power =1; power >0; power++)

{

total* =base

}

where does the power come into the equation?

"Ok this is how you do it:

- set total to 1,

- loop a power-number of times using the for-statement,

- each time in the loop multiply total times base."

Shadowplaya at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 21
> Man this is frustrating> > total = 1> for(power =1; power >0; power++)> {>total* =baseFirst produce something that'll compile. The code above won't.
prometheuzza at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 22

> Man this is frustrating

>

> total = 1

> for(power =1; power >0; power++)

> {

>total* =base

>

>

> where does the power come into the equation?

2^5 = 2 * 2 * 2 * 2 * 2 -- five 2s multiplied, which is also 1 * 2 * 2 * 2 * 2 * 2

(Using the 1 allows us to account for n^0 = 1, and to not need special handling for the first multiplication).

The loop, if done correctly (yours isn't), will start with 1 and then multiply by the base N times (e.g., 1, then multply by 2 five times).

jverda at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 23

> Man this is frustrating

>

> total = 1

> for(power =1; power >0; power++)

Can you explain what that loop control statement means? How many times will it execute? What will be power's value each time?

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html

jverda at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 24
If I'm trying to input two numbers, the base and the power that it wishes to be raised to, don't I need to initialize a power variable?
Shadowplaya at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 25

> If I'm trying to input two numbers, the base and the

> power that it wishes to be raised to

I know.

>, don't I need to

> initialize a power variable?

Yes, but what does that have to do with anything? I'm not sure which post you're addressing here. You'll want a power variable. We're not saying don't have one. We're saying you're using it incorrectly.

jverda at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 26

> > ...

>

> http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html

I already posted a link to it in reply #4 which the OP supposedly read.

I'm getting the impression the OP is not really interested in understanding it, but just wants to have something he/she can hand in.

prometheuzza at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 27

Hey I read it. And I understand how a for statement works. It's just tough trying to describe what problems I'm having with this problem. I have been reading java all day and my brain is a little fried right now. I really appreciate the help, and I'm trying to work through this myself. Right now I'm trying to figure out how exactly the for statement should read.

Shadowplaya at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 28
> Hey I read it. ...Then I was wrong. But you have yet to post some working code, so I'm still suspicious.Good luck anyway.
prometheuzza at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 29

> And I understand how a for statement

> works.

The for loop you posted suggests that you don't. I say this not to denigrate you, but to give you a dose of reality. I notice you didn't answer my question about what the control clause means. I posted that question to guage how much you actually do understand about the syntax and usage of for, so that I could tailor my advice appropriately.

> It's just tough trying to describe what

> problems I'm having with this problem. I have been

> reading java all day and my brain is a little fried

> right now.

It might be best to take a break then. Continuing to beat your head against a problem when you're already frustrated is often counterproductive.

jverda at 2007-7-21 17:29:59 > top of Java-index,Java Essentials,Java Programming...
# 30

A control clause indicates whether the loop should be terminated, I believe.

So in the statement

for(int a; a > 10; a ++)

the (a > 10) is the control clause and CONTROLS whether the for statement continues or the program flow exits out of the loop and goes to the next statement.

Am I far off track?

And you aren't going to denigrate me. I appreciate the help.

Shadowplaya at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 31

> A control clause indicates whether the loop should be

> terminated, I believe.

>

> So in the statement

>

> for(int a; a > 10; a ++)

>

> the (a > 10) is the control clause and CONTROLS

> whether the for statement continues or the program

> flow exits out of the loop and goes to the next

> statement.

>

> Am I far off track?

You're right, but I was looking for something more specfic--what each part of your specific for (blah; blah; blah) does and how it relates to your program.

So, in the one you provided:

> for(int ix; ix > 10; ix ++)

* It won't compile because you didn't give ix a value in the initialization part.

* Let's say you did the standardfor (int ix = 0; ...). So now we've initialized ix to 0.

* What does ix > 10 mean? When does it get executed?

* What does ix++ mean? When does it get exeucted?

* Based on the above two points, what can you say about how many times the loop body will execute?

jverda at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 32
And for the record, I think you ought to read that tutorial again, or at the very least refer to it carefully as you're constructing your loops. Understanding the basic idea how they work is necessary, but so is getting the syntax exactly right.
jverda at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 33

> > A control clause indicates whether the loop should

> be

> > terminated, I believe.

> >

> > So in the statement

> >

> > for(int a; a > 10; a ++)

> >

> > the (a > 10) is the control clause and CONTROLS

> > whether the for statement continues or the program

> > flow exits out of the loop and goes to the next

> > statement.

> >

> > Am I far off track?

>

> You're right, but I was looking for something more

> specfic--what each part of your specific for (blah;

> blah; blah) does and how it relates to your program.

>

> So, in the one you provided:

> > for(int ix; ix > 10; ix ++)

> * It won't compile because you didn't give ix a value

> in the initialization part.

>

> * Let's say you did the standardfor (int ix = 0;

> ...). So now we've initialized ix to 0.

>

> * What does ix > 10 mean? When does it get executed?

>

> * What does ix++ mean? When does it get exeucted?

>

> * Based on the above two points, what can you say

> about how many times the loop body will execute?

Ok, I understand that I didn't initialize the ix in the for statement.

The ix > 10 means that the loop will execute until ix becomes 11 or more, and the loop will execute 10 times because the ix++ is a post increment, meaning it won't increment until one full time through the loop.

I'm sure this is obvious but what I'm not sure of is what should go in the for loop. I believe it's the power that I'm raising the base to.

So I'm wondering if I should initialize a separate value called 'a' that initializes at ...zero? and increments until a is greater than the power variable.

Shadowplaya at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 34

> The ix > 10 means that the loop will execute until ix

> becomes 11 or more,

No. That's NOT the stopping condition, it's the "excute the body only if tihs is TRUE" condition.

So, ix > 10 (ix greater than 10) means execute the body only if ix is larger than 10.

The typical for loop idiom isfor (int ix = 0; ix < 5; ix++) {}

Meaning, init ix to 0, execute the body only as long as it's less than 5, and increment it after each execution. So 5 executions--0, 1, 2, 3, 4.

This is why I think you didn't read the tutorial closely enough. :-)

> and the loop will execute 10

> times because the ix++ is a post increment, meaning

> it won't increment until one full time through the

> loop.

No. Pre- vs. post-increment has NOTHING to do with the loop. ix++ and ++ix will cause exactly the same results there. The expression in that position doesn't have to be ix++; that's just the most common. Whatever expression is there will always be executed AFTER the body runs (if it runs at all).

Pre/post-inc comes into play in a situation like this:int ii = 0;

int jj = ii++; // value of the ii++ expression, is 0, so jj gets 0

int kk = 0;

int mm = ++kk;; // vlue of the ++kk expresssion is 1, so mm gets 1

> I'm sure this is obvious but what I'm not sure of is

> what should go in the for loop. I believe it's the

> power that I'm raising the base to.

Okay, a for loop is for doing the same thing a number of times. What are we doing over and over again?

On paper, 2^3 = 1 * 2 * 2 * 2. But that's not a single atomic operation. We do it as a number of steps.

Start with 1. Our total so far is 1

Multiply our total by 2. Our total is now 2.

Multiply our total by 2. Our total isnow 4.

Multiply our otal by 2. Our total is now 8.

> So I'm wondering if I should initialize a separate

> value called 'a'

I don't have all your code in front of me, so I don't know if you need another variable, but if you do, DON'T call it "a"--use a more descriptive name. That will also help you keep track of what you're doing.

jverda at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 35

So I've written this down on paper and now I'm just trying to iron out the bugs but I think this will work.

while (base > 0) // satisfies that no negative numbers are entered

{

for(int a =1; a > power; a++)

{

total *= base;

}

}

Any feedback? like I said I'm still trying to compile the code correctly

Shadowplaya at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 36

Okay, the while around the for is no good. That means that you'll do the whole for loop as long as base > 0. If you never change base, you'll do then enire for loop infinitely many times. If you change base from 2 to 1 to 0, then you'll do the for loop 3 times, meaning if for's body executes 5 times, you'll do 3 * 5 = 15 executions of for's body.

Get rid of the while loop completely. The only reason you'd use that is if you want to keep doing the power calculation until a user enters a negative number. Maybe that's what you're doing, but I can't see enough of your code to know.

And you still have this part wrong: for(int a =1; a > power; a++)

Did you even read my last post? It looks like you're doing exactly the same thing that I tried to correct.

And you're still using the meaningless "a" variable name.

When you post code, please use[code] and [/code] tags as described in [url=http://forum.java.sun.com/help.jspa?sec=formatting]Formatting tips[/url] on the message entry page. It makes it much easier to read.

jverda at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 37

Ok this is what I have so far. It isn't working but I think I'm close. BTW, it's not that I'm not reading your posts, it's just that sometimes I start writing and by the time I post, your reply is already out there.

import java.util.Scanner;

public class Homework614

{

public static void main( String args[] )

{

Scanner input = new Scanner(System.in);

int base;

int power;

int total = 1;

System.out.print( "Please enter a number");

base = input.nextInt();

System.out.print( "Please enter the power you wish to raise" );

power = input.nextInt();

if (base > 0)

{

for (int a = 1; a <= power; a++)

{

total = total * base;

}

}

System.out.printf( "The total is %d ", total);

}

}

AAARRRGGGGGHHHHH!!! It's obvious that my for loop here is the problem. I'm under the impression that you need two variables, a counter (in this case -a and what that variable will use as the condition to exit out of the loop.

Shadowplaya at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 38

> Ok this is what I have so far. It isn't working but

> I think I'm close. BTW, it's not that I'm not

> reading your posts, it's just that sometimes I start

> writing and by the time I post, your reply is already

> out there.

Okay, no problem. One of the hazards of forum communication.

> AAARRRGGGGGHHHHH!!! It's obvious that my for loop

> here is the problem.

What's going wrong? I didn't look too closely or try to run it, but it looks about right. It's pretty darn close at least.

> I'm under the impression that

> you need two variables, a counter (in this case -a

> and what that variable will use as the condition to

> exit out of the loop.

You've already go it: a (really, give it a better name. i at least, which is the standard loop counter, but I hate single letter variable names. Or count, or something), which is the counter for which iteration you're on, and power, which is the one to compare it against to decide whether to exit--that is, if power is 5, you want to do it 5 times, so you're counting a from 1 to 5 (though the standard approach would be 0 to 4).

Try printing out a, power, and total each time through the loop so you can see what's going on.

jverda at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 39
What happened when you ran it?
ejpa at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 40

Yeah it is working. I was having problems because I was forgetting, like an idiot, that if I tell it to raise five to the 5th power, then it doesn't mean 5 x5, it means 5 X 5 X 5 X 5 X 5.

Like you said, I probably need a break. Too bad I have four more questions to do.....

Thank you very much for your help. I need to give you all the credit since you figured out the logic for me. The total = total * base along with the for loop were the keys and you helped me a lot with the total part.

I appreciate you trying to talk me through the question. It only took five hours :).

Shadowplaya at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 41

> Yeah it is working. I was having problems because I

> was forgetting, like an idiot, that if I tell it to

> raise five to the 5th power, then it doesn't mean 5

> x5, it means 5 X 5 X 5 X 5 X 5.

D'OH! :-)

> Thank you very much for your help. I need to give

> you all the credit since you figured out the logic

> for me. The total = total * base along with the for

> loop were the keys and you helped me a lot with the

> total part.

No proble. I hope you'll be able learn not only the Java language issues involved but also the problem-solving and general programming.

> I appreciate you trying to talk me through the

> question. It only took five hours :).

You're welcome. It gets easier as you get more used to a certain way of thinking and get comfortable with the basics of the language. Starting out is hard because you need to learn both the principles and the langugae (and maybe tools, like a compiler or IDE, environment, like maybe Linux...)

jverda at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 42
Well, I'm going to keep posting if I have questions. I hope you guys don't find me annoying and decide to ignore me. :)
Shadowplaya at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 43

> Well, I'm going to keep posting if I have questions.

That's what the forum is for. Just a couple of suggestions:

* Really try to figure it out yourself before you post. I'm not saying you're not doing that, but after a long "conversation" like this, it can be very tempting to just lapse into, "Okay, here's the next problem. How do we do it?"

* If you've moved onto a different problem and have a different question, start a new thread.

> I hope you guys don't find me annoying and decide to

> ignore me. :)

There's usually somebody around, but we all answer what we want when we want for our own reasons, so don't assume you'll always get the quick turnaround you got here. (And resist the temptation to tell us how urgent it is as your deadline approaches. That's a major buzzkill for those of us who answer here as a low-stress escape from our own itme pressures.)

jverda at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 44

import java.util.Scanner;

public class Homework614

{

public static void main( String args[] )

{

Scanner input = new Scanner(System.in);

int base;

int power;

double total = 1.0;

System.out.print( "Please enter a number");

base = input.nextInt();

System.out.print( "Please enter the power you wish to raise" );

power = input.nextInt();

if (base != 0 && power >= 0)

{

for (int a = 1; a <= power; a++)

{

total = total * base;

}

}

else if (base != 0 && power < 0)

{

double b = 1.0 / base;

power = power * -1;

for (int a = 1; a <= power; a++)

{

total = total * b;

}

}

else if (base == 0 && power != 0)

{

total = 0;

}

else

{

//Do nothing (total = 1);

}

System.out.println( "The total is " + total);

}

}

Why do you use printf instead of print or println?

Carlemagnea at 2007-7-21 17:30:05 > top of Java-index,Java Essentials,Java Programming...
# 45

> import java.util.Scanner;

>

> public class Homework614

> {

>

> public static void main( String args[] )

> {

> Scanner input = new Scanner(System.in);

>

> int base;

> int power;

> double total = 1.0;

>

>

> System.out.print( "Please enter a number");

>

> base = input.nextInt();

> System.out.print( "Please enter the power you wish

> sh to raise" );

> power = input.nextInt();

>

> if (base != 0 && power >= 0)

> {

>

> for (int a = 1; a <= power; a++)

> {

> total = total * base;

> }

> }

>

> else if (base != 0 && power < 0)

> {

> double b = 1.0 / base;

> power = power * -1;

>

> for (int a = 1; a <= power; a++)

> {

> total = total * b;

> }

> }

>

> else if (base == 0 && power != 0)

> {

> total = 0;

> }

>

> else

> {

> //Do nothing (total = 1);

> }

>

>

>

> System.out.println( "The total is " + total);

> }

>

> }

>

>

>

> Why do you use printf instead of print or println?

I don't know. I tried it with both. Does it really matter?

Shadowplaya at 2007-7-21 17:30:09 > top of Java-index,Java Essentials,Java Programming...
# 46
If you want a newline, use println, and if you don't, don't.Usualy user input prompts don't have a newline:Enter whatever:<- User input goes here, instead of on the next line.
jverda at 2007-7-21 17:30:09 > top of Java-index,Java Essentials,Java Programming...