Creating pow in Java: Learn Recursive Solution

  • Context: Comp Sci 
  • Thread starter Thread starter cgrumiea
  • Start date Start date
  • Tags Tags
    Java
Click For Summary
SUMMARY

The discussion focuses on creating a recursive method named pow in Java that computes the power of an integer x raised to a non-negative integer n. Key insights include the base cases for recursion: pow(n, 0) = 1 and pow(n, k) = pow(n, k-1) * n. Participants emphasize the importance of checking the base case first to avoid infinite recursion. The provided code snippet demonstrates the initial structure of the method.

PREREQUISITES
  • Understanding of Java programming language
  • Familiarity with recursion concepts
  • Knowledge of integer operations in programming
  • Basic problem-solving skills in algorithm design
NEXT STEPS
  • Implement the pow method in Java with proper base case checks
  • Explore additional examples of recursion in Java
  • Learn about stack overflow issues related to deep recursion
  • Investigate iterative solutions for power calculations in Java
USEFUL FOR

Beginner Java developers, computer science students, and anyone interested in mastering recursion and algorithm design in programming.

cgrumiea
Messages
4
Reaction score
0

Homework Statement


Define a recursive method named pow that takes two integers, x and n, and returns the result of raising x to the n-th power. Assume that n is non-negative.

pow(5, 0) ==> 1
pow(2, 10) ==> 1024
pow(-3, 2) ==> 9



Homework Equations





The Attempt at a Solution


I'm totally fresh to java, and am not used to or comfortable with recursion.
public static int pow(int x, int n) {

I don't know what to do. Should I have some increasing value to count up to when x has been multiplied by itself n times? I know scheme which seems to be a bit of a different ball game here. Any help would be appreciated.
 
Physics news on Phys.org
pow(n,k)=pow(n,k-1)*n, isn't it? pow(n,0)=1. Isn't that a pretty recipe for recursion? You don't have to count anything at all.
 
yep, and remember to check the base case first:
Code:
if(k==1) return n;
or:
Code:
if(k==0) return 1;
if you will.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K