Question

In Java a function can call itself(we may explore more about this later in the course).  This...

  1. In Java a function can call itself(we may explore more about this later in the course).  This is called a “recursive function”. In order for this to work there must be a situation where the function finally stopscalling itself and simply returns a value (or just returns). We can use a Java ifstatement to make a recursive function return as required to make it work properly. This special case where the function finally returns is called the recursive function base case.

    Here is a simple example: a function to calculate the factorial of an integer number
    n>= 1. Remember that the factorial of n, n!, is n•(n-1)•(n-2)•…•1 if nis greater than or equal to 1. Factorial’s base caseoccurswhen n is 1èthe function should then return1; otherwise the function returns n•(n-1)!àby definition, n! isn•(n-1)! if n> 1.

    Here’s a Java recursive factorial function implementation, assuming nis at least 1:

       public static long factorial(int n)

   // header line: long return value since factorials grow rapidly!
   {
        if (n == 1) // this tests to see if nis 1, the base case
             return 1; // if so, the function returns 1
         
        return n*factorial(n-1); // assumes n >= 1

        // otherwise a recursive call – factorial calls itself!
        // this second returnexecutes if the ifcondition is false
   }


Your job for this part of the Lab is to create and testa similar recursive function that calculates and returns an integer power pof some integer number n; nand pare the parameters to the function, with header line staticlong power(int n, int p). You can assume that pis at least 0.Modify the above factorial function as follows:


Update the headerline for the function as above and then make these changes:

The base caseforthe powerfunction occurs when pis 0, at which point the function returns the value 1(by definition, any number raised to the 0 power is 1). To test for 0, the base case, replace the ifcondition with this one: if (p == 0).  

If pis not0 then the function should return n*power(n, p-1)ànpisnn(p-1)
if pis greater than 0. Use that information to change the second returnstatement.  

Now test to make sure powerworks by having maincall it with some known values and print out the results. For example, power(3, 2) should return 32=9,
power(-2, 7) should return (-2)7=-128, and power(8, 0) should return 1.

Derive Power.java from Factorial.java, and modify mainto test power.

Homework Answers

Answer #1

If you have any doubts, please give me comment...

public class Power {

    public static long power(int n, int p) {

        if (p == 0)

            return 1;

        else

            return n * power(n, p - 1);

    }

    public static void main(String[] args) {

        System.out.println("power(3,2) = "+power(3, 2));

        System.out.println("power(-2,7) = "+power(-2, 7));

        System.out.println("power(8,0) = "+power(8, 0));

    }

}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
There is a Java program that is missing one recursive function: public class Fibonacci { /*...
There is a Java program that is missing one recursive function: public class Fibonacci { /* / 0 when n = 0 * fib(n) = | 1 when n = 1 * \ fib(n-1)+fib(n-2) otherwise */ public static int fib(int n) { return 0; } /* Fibonacci Test Framework * * Note, this takes a long time to compute fib(44). */ public static void main(String[] args) { int[] input = { 11, 22, 33, 44}; int[] expect = { 89,...
Q1: Thefollowing code is supposed to return n!, for positive n. An analysis of the code...
Q1: Thefollowing code is supposed to return n!, for positive n. An analysis of the code using our "Three Question" approach reveals that: int factorial(int n){ if (n == 0)     return 1;   else     return (n * factorial(n – 1)); } Answer Choices : it fails the smaller-caller question.     it passes on all three questions and is a valid algorithm.     it fails the base-case question.     it fails the general-case question. Q2: Given that values is of...
Write a complete recursive java program to compute the heights of the tick marks on a...
Write a complete recursive java program to compute the heights of the tick marks on a ruler. Assume that the length of the ruler is a power of 2 (say L=2^n, where n >=1) , and the marks are to be placed at every point between 0 and 2^n, not including the endpoints. The endpoints 0 and 2^n will have height 0. Here are the rules for computing the heights of the ticks for a ruler of length L=2^n: 1....
*In Java Please RECURSION Objectives • Learn the basics of recursion – Part II (last week...
*In Java Please RECURSION Objectives • Learn the basics of recursion – Part II (last week was Part I) Submission Guidelines: You will turn in 2 program files (one for each lab problem) Tasks This lab has two parts: 1. Write a recursive method repeatNTimes(String s, int n) that accepts a String and an integer as two parameters and returns a string that is concatenated together n times. (For example, repeatNTimes ("hello", 3) returns "hellohellohello") Write a driver program that...
QUESTION 1 For the following recursive function, find f(5): int f(int n) { if (n ==...
QUESTION 1 For the following recursive function, find f(5): int f(int n) { if (n == 0)    return 0; else    return n * f(n - 1); } A. 120 B. 60 C. 1 D. 0 10 points    QUESTION 2 Which of the following statements could describe the general (recursive) case of a recursive algorithm? In the following recursive function, which line(s) represent the general (recursive) case? void PrintIt(int n ) // line 1 { // line 2...
//In this assignment, we implement a function that simulates the outcome of tossing of 3 dice....
//In this assignment, we implement a function that simulates the outcome of tossing of 3 dice. //We will learn how to generate random numbers, and how to seed a random number generator. //For example, we use the following code to generate a random number between 1 and 6. // rand() % 6 + 1 //The following code set the seed of the random number generator to 12345. // srand(12345); #include <stdio.h> #include <stdlib.h> #include <assert.h> //TO DO //Implement a function...
How to make the last element of an array null?(c++)So for my data structures class, we...
How to make the last element of an array null?(c++)So for my data structures class, we are working in c++. We are supposed to create a function that takes in an array, shifts everything to the left and leaves the original final element as null. Now I haven't found any simple way to convert them to null so I was just converting them to "0".I was seeking help on how to modify my code such to make the final element...
C++ please Write code to implement the Karatsuba multiplication algorithm in the file linked in Assignment...
C++ please Write code to implement the Karatsuba multiplication algorithm in the file linked in Assignment 2 (karatsuba.cpp) in Canvas (please do not rename file or use cout/cin statements in your solution). As a reminder, the algorithm uses recursion to produce the results, so make sure you implement it as a recursive function. Please develop your code in small The test program (karatsuba_test.cpp) is also given. PLEASE DO NOT MODIFY THE TEST FILE. KARATSUBA.CPP /* Karatsuba multiplication */ #include <iostream>...
There are two ways to write loops: (1) iterative, like the for-loops we're used to using,...
There are two ways to write loops: (1) iterative, like the for-loops we're used to using, and (2) recursive. Your prerequisite preparation for this course should have exposed you to both, although your working knowledge of recursive loops may not be as strong as that of iterative loops. Consider the following iterative function that prints an array of characters backward: #include <iostream> #include <cstring> // print an array backwards, where 'first' is the first index // of the array, and...
Coin Change Problem) Given a list of positive integers c[0...n − 1], and a positive integer...
Coin Change Problem) Given a list of positive integers c[0...n − 1], and a positive integer v, decides whether we can use numbers from c[0...n − 1] to make a sum of v, allowing any particular number in the list to be used multiple times. Or, mathematically, this means that there exists non-negative integer coefficients, x0, x1, ..., xn−1, such that v = x0c[0] + x1c[1] + ...xn−1c[n − 1]. For example, given c[0...3] = {2, 4, 6, 10}, and...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT