What's going on inside of this recursive function? - java

I have this recursive factorial function:
public class Driver{
public static void main (String args[])
{
System.out.println(factorial(5));
}
private static int factorial(int n)
{
int product;
if (n <= 2){ product = n; return 2;}
else{
product = n * factorial(n-1);
System.out.println("current product =" + product);
System.out.println("product = " + n + " * factorial(" + (n-1) + ")");
}
return product;
}
}
It prints the following:
current product =6
product = 3 * factorial(2)
current product =24
product = 4 * factorial(3)
current product =120
product = 5 * factorial(4)
120
I'm trying to figure out what the heck is going on here. I don't understand how it starts printing for n = 2. And where did current product = 6 come from? Thanks!

n==2 is your base case, so the first function to get past the below line is the one where n-1 == 2 or n == 3. This is because your output is performed after the recursive call, so it prints the deepest call first (thanks Patricia Shanahan) . If you want it to print from big to small, move your println lines above the line which calls factorial recursively.
product = n * factorial(n-1);
Also,
if (n <= 2){ product = n; return 2;}
This is wrong for so many reasons..
It should be
if (n <= 1){ return 1;}
If you are having trouble understanding this, remember that each call of factorial is independent of other calls.

Related

How to find the number of multiplications for x^63 using the exponent recursive function and how to justify it?

How would I go about justifying this algorithm is O(log n)?
public static long exponentiation(long x, int n){
if(n == 0){
return 1;
}
else if (n % 2 == 0){
x = exponentiation(x, n / 2);
return x * x;
}
else{
return x * exponentiation(x, n-1);
}
}
Each recursive call to method exponentiation is a multiplication step. Hence you need to count the number of recursive calls. There are several ways to achieve this. I chose to add another parameter to the method.
public static long exponentiation(long x, int n, int count) {
if (n == 0) {
System.out.println("steps = " + count);
return 1;
}
else if (n % 2 == 0) {
x = exponentiation(x, n / 2, count + 1);
return x * x;
}
else {
return x * exponentiation(x, n - 1, count + 1);
}
}
Here is the initial call to method exponentiation
exponentiation(2, 63, 0);
When I run the above code, the following is printed
steps = 11
You can use a static counter as well (without changing the prototype of the function):
public static long counter = 0;
public static long exponentiation(long x, int n){
if(n == 0){
return 1;
}
else if (n % 2 == 0){
x = exponentiation(x, n / 2);
counter++;
return x * x;
}
else{
counter++;
return x * exponentiation(x, n-1);
}
}
However, you need to reset the counter before calling the function each time, i.e., set counter = 0.
Theoretical Analysis
Note that you need to the counter to prove that it is in O(log(n)). To prove the complexity, just you need to find the complexity term by looking at the flow of the code. Suppose T(n) is the number of multiplications for computing x^n. So, based on the written code, T(n) = T(n/2) + 1, if n is even, and T(n) = T(n-1) + 1, if n is odd. Now, at least in one of two consecutive recursions, input n is even. Therefore, at most 2 log(n) is required to reach to n = 0. Because, for each even input, the next input will be halved. So, we can conclude that the algorithm is in O(log(n)).

Using Recursion to change digits in a number

I made this method for an assignment in class. To count the number of '1's appearing in any given number. I would like to expand on this and learn how to take a number and if it is even number adds one to it. If it is an odd number subtract one from it using recursion and return that changed number.
public static int countOnes(int n){
if(n < 0){
return countOnes(n*-1);
}
if(n == 0){
return 0;
}
if(n%10 == 1){
return 1 + countOnes(n/10);
}else
return countOnes(n/10);
}
0 would = 1 27 would = 36 so on. I would appreciate any help that is given.
You quite often find that using private method in a recursive solution makes your code much clearer.
/**
* Twiddles one digit.
*/
private static int twiddleDigit(int n) {
return (n & 1) == 1 ? n - 1 : n + 1;
}
/**
* Adds one to digits that are even, subtracts one from digits that are odd.
*/
public static int twiddleDigits(int n) {
if (n < 10) return twiddleDigit(n);
return twiddleDigits(n / 10) * 10 + twiddleDigit(n % 10);
}

Trying to calculate a factorial e^x, x being what the user enters, having trouble with the formula

I am in a Java class and it's still early in the class. The assignment is to:
e^x Approximations
The value ex can be approximated by the following sum:
1 + x + x^2/2! + x^3/3! + …+ x^n/n!
The expression n! is called the factorial of n and is defined as: n! = 1*2*3* …*n.
Write a program that takes a value of x as input and outputs four approximations of ex done using four different values of n: 5, 10, 50, and 100. Output the value of x the user entered and the set of all four approximations into the screen.
Sample formula use: calculating e^7 using approximation with n = 5
1 + 7 + 7^2/2! + 7^3/3! + 7^4/4! + 7^5/5!
I've got all the rest to work, including getting n to be 5, 10, 50 and 100. I thought I had the factorial formula figured out and I used the number 4 like the sample we were show and my numbers done match. Could really use another set of eyes.
Here's my code with forumla (x is the value the user enters and n is the 5, 10, 50 and 100):
/**
* myFact takes in x and calculates the factorial
* #param x
* #param n
* #return the factorial as a long
*/
public static long myFact(int x, int n) {
//declare variables
long sum = x;
for (int i=2; i <= n; i++) {
sum += ((Math.pow(x, i))/i);
}
return (sum + 1);
}
}
Here's the main class where I am calling the function. The error I suppose could be there too:
public static void main(String[] args) {
//declare variable for user input and call method to initialize it
int x = getNumber();
long fact;
int n;
//Output first line
System.out.println("N\t approximate e^" + x);
for (n = 5; n <= 100; n *= 2) {
if (n == 10) {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
n += 15;
} else {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
}
}
}
Thanks for taking a look at this, it's taken me hours to get this as the teacher gave us very little help.
You did a mistake in
sum += ((Math.pow(x, i))/i);
here you need to calculate the i!. Add below method in your code
public static int fact(int i){
int fact = 1;
for (int n = i; n > 0; n--) {
fact = fact * n;
}
return fact;
}
Also change sum += ((Math.pow(x, i))/i) to
sum += ((Math.pow(x, i))/fact(i));

Fibonacci Sum in (Java)

recently I have been working on an assignment to find the fibonacci sum of a number (user input, positive integer) in recursive form, for example (output is):
9 = 8 + 1
14 = 13 + 1
30 = 21 + 8 + 1
and so on.
So far, I have made the recursive function to calculate the actual fibonacci numbers (such as 8 and 1 in the sum of 9), it looks like this :
static long[] f = new long[50];
static long fib(int n) {
if (n <= 1) { //base case
return 1;
}
if (n < f.length) {
if (f[n] != 0) {
return f[n];
}
return f[n] = fib(n - 1) + fib(n - 2);
}
return fib(n - 1) + fib(n - 2);
}
My assignment gives me this as a hint:
Hints:
Re-cast the theorem as
n = fj + (n - fj )
This suggests a recursive solution.
and with that, I have currently come up with this:
static void fibSum(int n)
{
System.out.print(n + " = ");
for(int i = 0; i >= 0 ; i++)
{
if(n - (fib(i)) == 0)
{
System.out.println(fib(i));
}
else if(n < (fib(i)) && n > (fib(i-1)))
{
System.out.println(fib(i-1) + " + ");
}
}
}
My output goes as far as [entering for example, 9 as the user input] '9 = 8 +', and with that said, my question for all of those who are reading this (and thank you for getting this far!) is why I am not getting the last number (1) in the broken-down sum, and is my solution considered recurisve, as it really does not follow the format that I have seen in past examples, and in the fib() method that I wrote. I did not know how to implement printing the plus signs through that format.
Here is my main method for reference:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer number: ");
int n = scan.nextInt();
fibSum(n);
You seems to have various issues in your function fibSum:
Your For loop does not have an end. (while i is positive, increment i.)
You can store: fib(i) in your for loop to avoid multiple calculations.
You don't handle every cases on your if/else condition.
Exemple:
n = 2.
fib(0) = 1
if(2 - 1 == 0) => false
if(2 < 1 && 2 > fib(-1)) => false && error.
// Displays nothing. Should display: 2 = 1 + 1
Finally figured it out, this time using a while loop. No matter how many times I tried fixing the for loop, I ran into issues with my output, so I used a boolean variable and simply made it false once I reached n = 0.

Recursive method in Java is not working. Any ideas?

I am trying to understand the recursive methods in Java and tried this simple method to calculate a factorial.
Somehow it doesn't work. Can someone tell me why?
public class FactorialRecursive extends ConsoleProgram {
public void run() {
println("This program calculates the factorial of an integer n.");
int n = readInt("Please insert n: ");
int result = factorial(n);
println("The factorial of " + n + " is " + result);
}
private int factorial(int n) {
int total;
if (n == 1) total = 1;
total = n * factorial(n - 1);
return (total);
}
}
This is because your base case (n == 1) does not return right away.
You only assign total, but do not return: instead, you go with n * factorial(n-1) again, entering into infinite recursion.
Fix by replacing with
if (n==1) return 1;
or adding an else:
if (n==1) total = 1;
else total = n * factorial (n-1);
You are not terminating your recursion. Try
if (n==1) total = 1;
else total = n * factorial (n-1);
The issue is that you dont stop when you find your base case
if (n==1) total = 1;
Rather do
if (n==1) return 1;
Replace the line:
if (n==1) total = 1;
by:
if (n==1) return 1;
Otherwise, you'll loop infinitely.
Your method would be:
private int factorial(int n) {
return n==1 ? 1 : n * factorial (n-1);
}

Categories

Resources