Using recursion to compute factorials without new variables [duplicate] - java

This question already has answers here:
Recursion vs For loops - Factorials, Java
(3 answers)
Closed 6 years ago.
I am trying to compute the entered factorial in the method factorialRecursive by using recursion, However I cannot declare any variables or objects in that method and thats what i am struggling with, my attempt is in the method already but doesn't work. This has to call itself in a While loop not a for loop.
class Factorial{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = input.nextInt();
} while (number < 0);
System.out.println(number + "! = " + factorialIterative(number) + " (iterative)");
System.out.println(number + "! = " + factorialRecursive(number) + " (recursive)");
}
private static int factorialIterative(int num) {
int result = 1;
while (num > 0) {
result = num*result;
num--;
}
return result;
}
private static int factorialRecursive(int num){
if (num==1 | num==0)
return 1;
return num*(num-1) * num;
}
}

Try this:
private static int factorialRecursive(int num) {
// Warning here use || instead of |
if (num==1 || num==0)
return 1;
return num * factorialRecursive(num - 1);
}
I can also be simplified like this:
private static int factorialRecursive(int num) {
return (num == 1 || num == 0) ? 1 : num * factorialRecursive(num - 1);
}

You don't need to declare any variables. Take advantage of the recurrence relation for factorials:
n! = n * (n - 1)!
Multiply num by the result of making a recursive call by passing num - 1. Return that product without storing it in a variable.

Recursivity means you need to call the method itself inside of the method
Example:
private static int factorialRecursive(int num){
if (num==1 | num==0)
return 1;
return num*factorialRecursive(num-1);
}
and since factorial will increase really high with low values, consider to use other data type than integers... otherwise it will only work until factorial(16) after that you will get invalid data by using ints...
private static long factorialRecursive(long num){
if (num==1 | num==0)
return 1;
return num*factorialRecursive(num-1);
}

Related

Java print the recursion in main method

I was wondering when I tried to print the value of recursion in main, the answer was:
Enter the number: 1
2The result is:
How to make the number 2 to the front like,
The result is: 2
import java.util.Scanner;
public class Question4Final {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
System.out.printf("The result is: ", multiplication(a));
}
public static int multiplication(int a) {
if (a == 5) {
int multiply = 10 * 6 * 2;
System.out.print(multiply);
} else if (a == 4) {
int multiply2 = 6 * 2;
System.out.print(multiply2);
} else if (a == 1) {
System.out.print("2");
}
return a;
}
}
To call the method:
System.out.printf("The result is: ", multiplication(a));
first the arguments must be evaluated, so multiplication(a) is executed before System.out.printf("The result is: ", multiplication(a)). Since multiplication(a) prints something, that printing takes place before "The result is:" is printed.
You should change multiplication(a) to simply return the result without printing it. Then use System.out.println("The result is: " + multiplication(a)) to print the result.
Note the you have to change the value returned by multiplication(a), since currently you return a, which is not the value printed by that method.
You have 2 issues in your code.
First is you are printing the value of 'multiply' in your static method :
public static int multiplication(int a){
System.out.print(multiply);
That is a reason why it is printing 2 before the statement :
2The result is:
2nd issue is you are calling the method multiplication in the print statement :
System.out.printf("The result is: ", multiplication(a));
That is not how to print the result by calling the method.
I have taken your example and run the below code. You can check this code.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
int product = multiplication(a);
System.out.println("The result is : " +product);
}
public static int multiplication(int a){
int multiply = 0;
if(a == 5){
multiply = 10 * 6 * 2;
}else if(a == 4){
multiply = 6 * 2;
}else if(a == 1){
multiply = 2;
}
return multiply;
}
}
Below are the outputs on different options :
Enter the number: 4
The result is : 12
Enter the number: 5
The result is : 120
Enter the number: 1
The result is : 2

how to show the negative number factorial in this code

im trying to make a calculator and im was unable to continue because of some confusion in my codes. i was trying to make a factorial of a number, if its a positive number there is no error but every time i input a negative number it results to 1, here is my code .
import java.math.BigInteger;
import java.util.Scanner;
public class Factorial2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = s.nextInt();
String fact = factorial(n);
System.out.println("Factorial is " + fact);
}
public static String factorial(int n) {
BigInteger fact = new BigInteger("1");
for (int i = 1; i <= n; i++) {
fact = fact.multiply(new BigInteger(i + ""));
}
return fact.toString();
}
}
i already tried making if statements but still it results to 1.i also want to make the negative factorial into a display text not the value of the negative factorial
You need to validate the input before the calculation, example:
public static String factorial(int n) {
if(n < 1) return "0";
BigInteger fact = new BigInteger("1");
for (int i = 1; i <= n; i++) {
fact = fact.multiply(new BigInteger(i + ""));
}
return fact.toString();
}
Of course you can define any default return value or throw an error:
if(n < 1) throw new RuntimeException("Input must be > 0");

having a variable in recursive method not redefine itself after each call

I am going to post my code below because this is kind of hard to describe. The code below works, but it is using Math.pow in the main method rather than in the helper, so if someone could show me a way to move the power to the helper method without messing up the program that would be much appreciated.
Main method:
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer: ");
double input = keyboard.nextInt();
double x = Math.pow(2.0, input);
int n = (int)x;
System.out.println(starStr(n));
Helper method:
public static String starStr(int n)
{
if (n >= 1) {
return ("*" + starStr(n-1));
}
else {
return "";
}
}
EDIT:
if(n == 0) {
return "*";
}
else {
return starStr(n - 1) + "**";
}
Something like this would work. You don't really need to use a power function at all. Just start with 1 star and double the number of stars in every step of the recursion.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer for the number of stars: ");
int input = keyboard.nextInt();
System.out.println(doStars(input));
}
public static String doStars(int n)
{
//If n == 0 the recursion is done
//Otherwise, reduce n by 1 and double the number of stars
if(n == 0)
return "*";
else
{
String output = doStars(n - 1);
return output + output;
}
}
I think this is what you are looking for. Not sure if you have learned the tree data-structure, but that's the purpose of my variable names.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
// 1 + (2^n)-1 = 2^n
System.out.println("*" + doStars(i));
}
}
public static String doStars(int n)
{
if (n == 0) {
return "";
}
else {
String subTree = doStars(n - 1);
return subTree + "*" + subTree; // length = (2^n)-1
}
}
}
Output
*
**
****
********
****************
Visualization - read clockwise in triangles from little to big
"*"
+
doStars(2)
"*"
doStars(1) + doStars(1)
"*" "*"
doStars(0) + doStars(0) doStars(0) + doStars(0)
"" "" "" ""

I am getting a Cannot find symbol error that I can't resolve

I am getting this error that to me looks like I am not calling the method correctly. I have reviewed the past answers here but none have specifically addressed my problem as far as I can see. This is for a class project. I realize my math in the method is most likely not correct yet but I need to get the rest working then deal with an incorrect out put. Thanks a lot!
Here is my code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse);
}
public static int reverse(int num, int rNum) {
rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}
And My error Message:
PrintOutNumbersInReverse.java:28: error: cannot find symbol
System.out.println ("Your number in reverse is: " +reverse);
^ symbol: variable reverse location: class PrintOutNumbersInReverse 1 error
Change method implementation to:
public static int reverse (int num)
{
int rNum = 0;
...
return rNum;
}
and place, that is calling this method to:
System.out.println ("Your number in reverse is: " +reverse(num));
Then should be fine
When copy pasting this into eclipse, i noticed 2 things:
1.) your reverse() method doesn't return an int, but it should because the signature of the method says so: public static int reverse(int num, int rNum). Maybe return rNum, or whatever the logic behind it might be?
2.) second, you have not declared any reverse variable in the main method. Maybe you wanted a parameterized call of reverse()?
Also it looks like, you want in the reverse() method rNum to be an output parameter. In java you can't pass primitives by reference, so whatever you do with rNum inside the method, the changes will only be present in the scope of the method. So you might want to calculate something and actually return the results of your calculations.
You need to use reverse as a method, and not a variable. Also, you are passing in a variable that is not used: rNum. You see in reverse(int num, int rNum); right after you start, it sets your rNum to 0. So why pass a number in that will get set to zero?
I did this from my phone, but this should be working code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse(num)); //<-- notice how this is a method cause it has "()"
}
public static int reverse(int num) { //<-- this has "int num" in the "()". This is a parameter.
int rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}

Java: Invoking Methods From Class / null logic error

I'm having a hard time wrapping my head around object based programming. Im attempting to invoke a method from a class. However, all I invoke is a variable that has been declared, while I'm trying to pull the variable later. (Im sure my terminology is off - feel free to correct)
Im getting logic errors. Instead of a value, im getting "null".
The Class:
public class NumberOperations {
int number;
String oddsUnder;
String powersTwoUnder;
int isGreater;
String toString;
public NumberOperations(int numberIn) {
number = numberIn;
}
public int getValue() {
return number;
}
public String oddsUnder() {
String output = "";
int i = 0;
while (i < number) {
if (i % 2 != 0) {
output += i + "\t";
}
i++;
}
return output;
}
public String powersTwoUnder() {
String output2 = "";
int powers = 1;
while (powers < number) {
output2 += powers + "\t";
powers = powers * 2;
}
return output2;
}
public int isGreater(int compareNumber) {
if (number > compareNumber) {
return 1;
}
else if (number < compareNumber) {
return -1;
}
else {
return 0;
}
}
public String toString() {
return number + "";
}
}
The Program:
import java.util.Scanner; import java.util.ArrayList;
/** * Demonstrates the NumberOperations class. */ public class NumberOpsDriver {
/**
* Reads a set of positive numbers from the user until the user enters 0. * Prints odds under and powers of 2 under for each number. *
* #param args - Standard commandline arguments
*/ public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// declare and instantiate ArrayList with generic type <NumberOperations>
ArrayList<NumberOperations> numOpsList = new ArrayList<NumberOperations>();
// prompt user for set of numbers
System.out.println("Enter a list of positive integers separated "
+ "with a space followed by 0:");
// get first user input using in.nextInt()
int firstInput = in.nextInt();
// add a while loop as described below:
while (firstInput != 0) {
numOpsList.add(new NumberOperations(firstInput));
firstInput = in.nextInt();
}
// while the input is not "0"
// add NumberOperations object to array based on user input
// get the next user input using in.nextInt()
int index = 0;
while (index < numOpsList.size()) {
NumberOperations num = numOpsList.get(index);
System.out.println("For: " + num);
System.out.println("Odds under: " + num.oddsUnder);
System.out.println("Powers of 2 under: " + num.powersTwoUnder);
// add print statement for odds under num
// add print statement for powers of 2 under num
index++;
} } }
You never assign to your member variables oddsUnder and powersTwoUnder. So of course they are null when you read them, and when you try to print them you have a NullPointerException it prints "null".
You probably actually want to call the methods of the same name instead of taking the variables
System.out.println("Odds under: " + num.oddsUnder());
System.out.println("Powers of 2 under: " + num.powersTwoUnder());
Make your properties as private to avoid this kind of situations and change your properties in System.out... to call the methods not the object fields. For example
System.out.println("Odds under: " + num.oddsUnder()); //<-changed

Categories

Resources