Trying to build a String using recursion in Java - java

I'm trying to build the following string using recursion in Java. The expected output is:
4! = 4!
= 4 * 3!
= 4 * 3 * 2!
= 4 * 3 * 2 * 1!
= 4 * 3 * 2 * 1 * 0!
This is my factorial method:
public static String factorial(int n, int count, String equation)
{
if (n == 0) {
return equation += (n + "!");
} else {
equation += (n - count);
return factorial(n - 1, count, equation);
}
}
I'm entering the following input in my main method:
System.out.print(factorial(4, 0, ""));
It currently prints out the String "43210!" I haven't worked with recursion much. What am I doing wrong?

I changed some your code,then code can achieve one's goals.here is the code.I hope this can help you.
public class Snippet {
public static String factorial(int n, String equation)
{
if (n == 0) {
return equation += (n + "!");
} else {
equation += (n + "*");
return factorial(n - 1, equation);
}
}
public static void factorial1(int n, String equation)
{
if(n < 0)
{
return;
}
System.out.println(equation + n + "!");
factorial1(n - 1, equation + n + "*");
}
public static void main(String [] arg)
{
System.out.println("4! ");
System.out.println(factorial(4, "="));
System.out.println();
factorial1(4, "=");
}
}

If you want to achieve your goal using only one recursion function, it will require nested recursion. You might want to try something like following:
public class Factorial {
public static void main(String[] args) {
System.out.println(factorial(4));
}
private static String factorial(int origNum, int lineNum, int innerLoopNum, String equation) {
if(innerLoopNum == origNum - lineNum) {
equation = equation + innerLoopNum + "!" + "\n";
}
else if(lineNum > origNum)
return equation;
else {
equation = equation + innerLoopNum + "*";
equation = factorial(origNum, lineNum, --innerLoopNum, equation);
return equation;
}
++lineNum;
if(lineNum > origNum)
return equation;
return factorial(origNum, lineNum, origNum, equation);
}
public static String factorial(int n) {
return factorial(n, 0, n, "");
}
}

Assuming that n will never be negative, this should suffice...
public String factorialString(int n) {
if (n == 0) return "0!";
return n + " * " + factorialString(n - 1);
}
Just for fun, you can also write it as:
public String factorialString(int n) {
return (n == 0)
? "0!"
: n + " * " + factorialString(n - 1);
}
For people concerned, I know I am doing a string concatenation and I should use a StringBuilder instead. The task is to demonstrate recursion here.

Related

How to find factorial and show result of counting in console?

public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+"!="+factorial(n));
}
public static int factorial(int num) {
return (num == 0) ? 1 : num * factorial (num - 1);
}
}
how make this code to text in console 3! = 1*2*3 = 6?
Don't use recursion for this. Besides, it isn't really efficient or necessary.
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int fact = 1;
String s = n + "! = 1";
for (int i = 2; i <= n; i++) {
fact *= i;
s += "*" + i;
}
s += " = ";
System.out.println(s + fact);
There can be many ways to do it e.g. you can build the required string or print the trail while calculating the factorial. In the following example, I have done the former.
As an aside, you should check the input whether it is a positive integer.
import java.util.Scanner;
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = in.nextInt();
if (n >= 0) {
StringBuilder strFact = new StringBuilder();
int fact = factorial(n, strFact);
if (strFact.length() > 0) {
// Delete the last '*'
strFact.deleteCharAt(strFact.length() - 1);
System.out.println(n + "!= " + strFact + " = " + fact);
} else {
System.out.println(n + "!= " + fact);
}
} else {
System.out.println("This is an invalid input.");
}
}
public static int factorial(int num, StringBuilder strFact) {
int fact;
if (num == 0) {
fact = 1;
} else {
fact = num * factorial(num - 1, strFact);
strFact.append(num + "*");
}
return fact;
}
}
A sample run:
Enter an integer: 3
3!= 1*2*3 = 6

Palindrome checker seems to dump every digit above a single character into my else statement

I have performed some tests, when I switch this section to isPali = True:
else{
isPali = false;
p = n;
}
All my numbers tested are considered palindromes. So for some reason any numbers I have above two characters are simply being dumped into the else. I tried desk checking but have been unable to determine why.
Output when run normally is 0 to 9 then nothing.
public class Palindromorizor{
public static void main (String[] args){
String inputString, limit;
int n, p, numLim, num = 0;
boolean isPali;
limit = JOptionPane.showInputDialog("What is your limit?");
numLim = Integer.parseInt(limit);
while(num < numLim){
isPali = isPalindrome(num);
if(isPali == true){
System.out.print(num + " ");
++num;
}
else{
++num;
}
}
}
public static boolean isPalindrome(int num){
String strNum;
int n = 0;
int p;
boolean isPali = true;
strNum = "" + num;
p = strNum.length();
//strNum.substring(p - 1, p) + " " + p + " " + n + " " + strNum + " " + isPali);
while(p > n){
if(strNum.substring(n, n + 1) == strNum.substring(p - 1, p) && (p <= n)){
isPali = true;
}
else if(strNum.substring(n, n + 1) == strNum.substring(p - 1, p) && (p > n)){
++n;
--p;
}
else{
isPali = false;
p = n;
}
}
return isPali;
}
}
Because you are comparing Strings with == operator. Use equals method.

Using recursion, in java, to have a variety of outputs from a single int parameter

If anyone is familiar with PracticeIt, it's what I'm doing and I'm on recursion problem sets. I'm having trouble doing them. Here's one problem:
Write a method writeSquares that accepts an integer parameter n and prints the first n squares separated by commas, with the odd squares in descending order followed by the even squares in ascending order. The following table shows several calls to the method and their expected output:
writeSquares(5); ----> Output: 25, 9, 1, 4, 16
writeSquares(1); ----> Output: 1
I've spent a few hours each day for the past 3 days figuring out recursions but I just can't figure it out.
Can anyone point me in the right direction?
My code looks like:
public static void writeSquares(int n)
{
if(n<1)
throw new IllegalArgumentException();
else{
if(n%2==0){
System.out.print((n-1)*(n-1));
writeSquares2(n-1, n-1, "down");
}
else{
System.out.print(n*n);
writeSquares2(n-1, n-1, "down");
}
}
}
public static void writeSquares2(int n, int m, String s)
{
if(m==0){
return;
}
String ss = s;
if(n<=1){
ss = "up";}
if(n%2==1&&s=="down"){
System.out.print(", " + n*n);
writeSquares2(n-2,m-1,ss);
}
if(n%2==0&&s=="down"){
writeSquares2(n-1,m-1,ss);
System.out.print(", " + n*n);
}
if(n%2==1&&s=="up"){
System.out.print(", " + n*n);
writeSquares2(n+2,m-1,ss);
}
if(n%2==0&&s=="up"){
writeSquares2(n+1,m-1,ss);
System.out.print(", " + n*n);
}
EDIT: Woops I fixed the code below
And another question from another problem set is:
Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed by ascending integers beginning with 1, as in the table below:
writeSequence(9); -----> 5 4 3 2 1 2 3 4 5
writeSequence(10); -----> 5 4 3 2 1 1 2 3 4 5
My code:
public void writeSequence(int n)
{
if(n<1)
throw new IllegalArgumentException();
else
writeSequence2(n, n, "down"); //I actually dont need the second parameter
}
public void writeSequence2(int n, int m, String s)
{
String ss = s;
if(n/2-1==1)
ss = "up";
if(n==1)
System.out.print(n);
else if(ss.equals("down")){
if(n%2==0){
System.out.print(n/2+" ");
writeSequence2(n-1, m-1, ss);
}
else if(n%2==1){
writeSequence2(n-1, m-1, ss);
System.out.print(" "+ (n/2+1));
}
}
else if(ss.equals("up")){
if(n%2==0){
System.out.print(n/2+" ");
writeSequence2(n-1, m-1, ss);
}
else if(n%2==1){
writeSequence2(n-1, m-1, ss);
System.out.print(" " + (n/2+1));
}
}
}
For the second one, my code is somewhat correct. Except when n is odd.
Also another question - is it possible to do these with just a single method?
Thanks for your time. The tutors in my school aren't very helpful and neither are my classmates.
public void writeSequence(int n){
if( n < 1){
throw new IllegalArgumentException();
}
if(n==1){
System.out.print(n);
}
else if(n==2){
System.out.print(n/2 +" " + n/2);
}
else if(n%2 ==0){
System.out.print(n/2 +" ");
writeSequence(n-2);
System.out.print(" " +n/2);
}
else if(n%2 ==1){
System.out.print( (n/2+1) +" ");
writeSequence(n-2);
System.out.print( " "+(n/2 +1));
}
}
I realize this is an old thread but in case anyone still gets directed to this page, I just had this question as well. this is how I answered it without a helper method. by the way its really close to Eran's 1st answer except I took my writeSequence out of the if statement. this worked.
public void writeSquares(int n) {
//for exception
if (n < 1) {
throw new IllegalArgumentException();
//for base
} else if (n == 1) {
System.out.print("1");
return;
}
//printing evens before base
// commas trail number now
if ((n % 2) != 0) {
System.out.print((n * n) + ", ");
}
//does this until base
writeSquares(n - 1);
//then as we start coming back out of the method calls print evens
// commas before lead numbers now
if ((n % 2) == 0) {
System.out.print(", " + (n * n));
}
}
Create two arraylists that EvenList and oddList
if squared value matches even condition put it in evenList, else in oddList.
First print oddList in reverse order and print evenList as it is from index 0.
The idea is that if n is odd, you want to print n*n immediately (which would print the odd squares in descending order), and then make a recursive call with n-1, while if n is even, you first make the recursive call with n-1 and then print n*n (which would print the even squares in ascending order after all the odd squares are printed).
public static void writeSquares(int n){
if(n<1)
throw new IllegalArgumentException();
if (n==1)
System.out.print(1 + ",");
else if (n % 2 == 1) {
System.out.print(n*n + ",");
writeSquares (n - 1);
} else {
writeSquares (n - 1);
System.out.print(n*n + ",");
}
}
EDIT : this code would produce an extra , at the end.
25,9,1,4,16,
To get rid of that, you might have to add a boolean parameter to the method, which indicates whether it's the first call to the method or not.
For writeSequence, the idea is to solve the problem for n assuming you already have the solution for n - 1. If you have a method the writes the sequence for n - 1, in order to expand it to n, you have to print n, print the sequence for n - 1, and print n again. In addition, you need a stopping condition, which is n==1, in which case you just print 1.
public static void writeSequence(int n)
{
if(n<1)
throw new IllegalArgumentException();
if (n==1)
System.out.print(1 + " ");
else {
System.out.print(n + " ");
writeSequence (n-1);
System.out.print(n + " ");
}
}
EDIT:
I missed some details in the question about the second recursion. Here's the updated method. I'm not sure if it's possible to have all the logic in a single method. I had to split it to two recursive methods, based on whether n is odd or even.
public static void writeSequence(int n)
{
if (n%2 == 0)
writeSequenceEven (n);
else
writeSequenceOdd (n);
}
public static void writeSequenceOdd(int n)
{
if (n == 1) {
System.out.print (1 + " ");
} else if (n>1) {
System.out.print((1+n/2) + " ");
writeSequenceOdd (n-2);
System.out.print((1+n/2) + " ");
}
}
public static void writeSequenceEven(int n)
{
if (n>1) {
System.out.print(n/2 + " ");
writeSequenceEven (n-2);
System.out.print(n/2 + " ");
}
}
Here is my solution, it's pretty compact and should work.
public static void writeSequence(int n) {
if (n <= 1){
System.out.print(1);
} else if (n % 2 != 0){
System.out.print(n*n + ", ");
writeSequence(n-1);
} else{
writeSequence(n-1);
System.out.print(", " + n*n );
}
}

How to convert this while loop into recursion?

I'm trying to solve this problem but in stuck in converting my while loop into recursion
Ive managed to implement the printMany function as follows
public static void printMany(int count, String s){
if(count >= 1) {
System.out.print(s);
printMany(count-1, s);
}
}
But the current implementation of the hourglass method still uses loops though it displays the correct output.
public static void hourglass(int numberOfStars, int numberOfSpaces){
while(numberOfStars>0){
printMany(numberOfSpaces++, " ");
printMany(numberOfStars--, "X ");
System.out.println();
}
numberOfSpaces -=2;;
numberOfStars += 2;
while(numberOfSpaces>=0){
printMany(numberOfSpaces--, " ");
printMany(numberOfStars++, "X ");
System.out.println();
}
}
I want to ask, how can I convert this while loop into a recursive call?
I'm not just going to give you the answer, but I'll try to help you along. If you want to break this down using recursion and without loops, the key really is to figure out what the parameters of your recursive helper function must be. It seems like you will always need to remember the original user input (to know how many spaces to print out and to know when to stop the recursion), the current number of stars you're on, and whether you're on the top half of the pyramid or the bottom half. Given all of that information, you should be able to do two things. First, you should be able to correctly print out a line. Second, you should be able to determine what the next line should be. Given this, you can print and recurse, stopping once your base case is reached.
This is one possible solution:
public static void printMany(int count, String s) {
if (count == 0)
return;
System.out.print(s);
printMany(count - 1, s);
}
public static void upperhalf(int count, int max) {
if (count == 0)
return;
printMany(max - count, " ");
printMany(count, "* ");
System.out.println();
upperhalf(count - 1, max);
}
public static void lowerhalf(int count, int max) {
if (count == max)
return;
printMany(max - count - 1, " ");
printMany(count + 1, "* ");
System.out.println();
lowerhalf(count + 1, max);
}
public static void hourglass(int n) {
upperhalf(n, n);
lowerhalf(0, n);
}
Calling hourglass(1); within e.g. main results to:
*
*
So hourglass(2); prints:
* *
*
*
* *
And so on...
Instead of a while looping your program you call the same function.
public static void hourglass(int numberOfStars, int numberOfSpaces){
hourglass(numberOfStars, numberOfSpaces, false);
}
private static void hourglass(int numberOfStars, int numberOfSpaces, boolean dir){
if(dir==false && numberOfStars > 0){
printMany(numberOfSpaces, " ");
printMany(numberOfStars, "X ");
System.out.println();
hourglass(--numberOfStars, ++numberOfSpaces, false);
return;
}
if(numberOfStars==0){
numberOfSpaces -=2;
numberOfStars += 2;
}
if(numberOfSpaces>0){
printMany(numberOfSpaces, " ");
printMany(numberOfStars, "X ");
System.out.println();
hourglass(++numberOfStars, --numberOfSpaces, true);
}
}
Here's a piece of code for you. Used symmetrical padding.
public class Hourglass {
public static void printRow(int nStars, int padding) {
if (nStars == 0)
return;
if (padding > 0) {
System.out.print(" ");
printRow(nStars, padding - 1);
System.out.print(" ");
return;
}
if (nStars <= 0)
return;
System.out.print("*");
if (nStars > 1) {
System.out.print(" ");
printRow(nStars - 1, padding);
}
}
public static void printTop (int height, int padding) {
if (height == 0)
return;
printRow(height,padding);
System.out.print("\n");
printTop(height - 1, padding + 1);
}
public static void printBottom(int currentHeight, int height, int padding) {
printRow(currentHeight, padding);
System.out.print("\n");
if (currentHeight < height)
printBottom(currentHeight + 1, height, padding - 1);
}
public static void printHourglass(int height) {
if (height <= 0)
throw new IllegalArgumentException();
printTop(height, 0);
printBottom(1, height, height - 1);
}
public static void main(String[] args) {
printHourglass(5);
}
}
Just split that method into two, here's another recursion solution for your question:
public static void hourglass(int numberOfStars, int numberOfSpaces) {
if(numberOfStars== 0) return;
printMany(numberOfSpaces++, " ");
printMany(numberOfStars--, "X ");
System.out.println();
hourglass(numberOfStars,numberOfSpaces);
numberOfSpaces -=2;
numberOfStars += 2;
if(numberOfStars==2)
hourglassBottom(numberOfStars,numberOfSpaces);
}
public static void hourglassBottom(int numberOfStars, int numberOfSpaces){
if(numberOfSpaces==0 )return;
printMany(numberOfSpaces--, " ");
printMany(numberOfStars++, "X ");
System.out.println();
hourglassBottom(numberOfStars,numberOfSpaces);
}
For example, running hourglass(3,1); would give you following:
X X X
X X
X
X X
X X X

Ask users if user wishes to re-run the program

I wrote the following program which displays if a number is a prime and if not a prime it display its prime factors and the next prime number.
However, I am not sure how to have the program ask the user if he/she wishes to input another number.
The user must answer either yes, no, y or n using any combination of lower and upper case letters.
If an invalid answer is given, the program must be informed that the answer was not acceptable, and then be prompted again for another answer. The program will only prompt up to three tries otherwise the program will exit.
If the answer is Yes (in any allowed form), the program must continue from step in the main function.
The program is written in prototype methods because that is what is called for.
If anyone can assist a newbie with the last part, i would greatly appreciate it.
code:
package primefactors;
import java.util.Scanner;
public class Primefactors {
//------------------three tries check method-------------------
public static int getNumberWithThreeTries(int m) {
int count = 1;
int number;
String s = "tries";
while (count <= 3) {
number = getInputNumber(m); //getScore returns -1 for invalid inputs
if (number <= 1) {
if ((3 - count) < 2) {
s = "try"; //just make sure that singular /plural form in the next statme is correct
}
if (count == 3) {
System.out.println("No more tries remaining!\n");
} else {
System.out.println((3 - count) + " " + s + " remaining! Try Again! \n");
}
count = count + 1;
} else {
return number;
}
}
return -1;
}
//-------------------boolean try again---work in progress---------------
public boolean askRunAgain() {
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean askRunAgain = scanner.nextBoolean();
return askRunAgain;
}
//----------------------------------boolen prime check method------------------
public static boolean isPrime(int m) {
for (int i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
}
return true;
}
//------------------------next prime method-----------------
private static int nextPrime(int m) {
if (m % 2 == 0) {
m = m + 1;
}
for (m = m; !isPrime(m); m = m + 2)
;
return m;
}
//---------------------primefactors----------------------
public static String getPrimeFactors(int m) {
String ans = "";
for (int i = 2; i <= m; i = i + 1) {
if (m % i == 0) {
ans += i + "*";
m = (m / i);
i--;
}
}
return (ans.substring(0, ans.length() - 1));
}
//----------------------------------------------------------
public static int getInputNumber(int m) {
Scanner n = new Scanner(System.in);
int number = 0;
System.out.println("Enter an Integer greater than 1");
if (!n.hasNextInt()) {
System.out.print("That's not a number! you have ");
n.next();
return -1;
}
number = n.nextInt();
if (number <= 1) {
return -1;
}
return number;
}
//------------------------------main method ----------------------
public static void main(String[] args) {
int number;
int count = 0;
number = getNumberWithThreeTries(1);
if (number <= 1) {
System.out.println("Program Terminated");
System.exit(0);
}
if (isPrime(number)) {
System.out.println(number + ": Is a Prime Number \n\n"
+ getPrimeFactors(number) + ": Is its prime factor");
} else {
System.out.println(number + " Is not a Prime number\n\n"
+ getPrimeFactors(number) + " Are its prime factors \n\n"
+ nextPrime(number) + " Is the next Prime number\n ");
}
}
}
You need to place the getNumberWithThreeTries within a while loop, which at the end, ask if the user wants to try again. If they say yes, then your while loop should then continue to execute again, otherwise, it should exit.

Categories