Fibonacci Recursion in Java - No For Loops? - java

I don't understand what I should be doing. My professor wants us to create a Fibonacci sequence using recursion. No for loops are allowed, and I (being an amateur) don't know how to create a String of say, 6 numbers in sequence.
Here are his directions: "Using recursion, create a method that returns a String containing a Fibonacci sequence. Take in an integer to determine how many values of the sequence you should return."
This is what I have thus far...
import java.util.*;
public class fibo {
public final static int n = 0;
public static String s = "";
public static void main(String[] args) {
Scanner scn = new Scanner (System.in);
System.out.println("Please put in a number.");
int n = scn.nextInt();
s = Integer.toString(n);
System.out.println(n+ ": " + fibonacci(n));
}
public static int fibonacci(int n) {
if(n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
In addition to that, I feel like a lot of it is really inefficient and messy. Can someone really explain and help me with what I should be doing?

It looks like you are generating the nth number in the Fibonacci sequence, it seems to me, you need to store all the values you are generating (not just the last one) and display them.
So rather than just f(n), you need to display f(1), f(2), ..., f(n-1), f(n) once you have done that you have completed your assignment.

This should work just fine:
public class Fibonacci {
  public static void main(String[] args) {
    System.out.println(Fib(3));
  }
  // returns the next number in the Fibonacci sequence
  public static int Fib(int n) {
    if (n < 2) {
      return n;
    } else {
      return Fib(n - 1) + Fib(n - 2);
    }
  }
}

Here is Code which works good, without unnecessary Code.
import java.util.*;
public class Fibonaccis {
public static void main(String[] args) {
Scanner scn = new Scanner (System.in);
System.out.println("Lägg in ett nummer.");
int n = scn.nextInt();
System.out.println(n+ ": " + fibonacci(n));
}
// TODO Auto-generated method stub
public static int fibonacci(int n) {
if(n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

This code showing Fibonacci till 8 without any loop...
public class FinnonnacciDemo2 {
static int no = 0, n = 8;
public static void main(String[] args) {
// This will print series till 8
fib(0, 1);
}
public static void fib(int a, int b) {
// Terminating condition.
if (a >= n) {
return;
}
else {
System.out.print("\t" + no);
no = a + b;
a = b;
b = no;
fib(a, b);
}
}
}

Related

Setting up a global variable to count recursions

public class collatzpow {
public static int collatz(int n) {
StdOut.print( n + " ");
if (n == 1) return 0;
if (n% 2 == 0) return collatz(n/2);
else return collatz(3*n + 1);
}
public static void main(String[] args) {
int n= Integer.parseInt(args[0]);
StdOut.println(collatz(7));
}
}
I want to set up a global variable to count the number of time the program calls the recursion. I know with the number 7 it calls it 17 times.
I've been told it is very easy, but I'm struggling a bit with it.
Just declare a static int variable in the class scope and increment each time the method is called.
public class collatzpow {
public static int count = 0;
public static PrintStream StdOut = System.out;
public static int collatz(int n) {
++count;
StdOut.print(n + " ");
if (n == 1) return 0;
if (n % 2 == 0) return collatz(n / 2);
else return collatz(3 * n + 1);
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
StdOut.println(collatz(7));
System.out.println(count);
}
}

StackOverFlowError in java program [duplicate]

This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 7 years ago.
I am trying to solve a problem which asks to find the smallest prime palindrome, which comes after a given number which means that if the input is 24, the output would be 101 as it is the smallest number after 24 which is both prime and a palindrome.
Now my code works perfectly for small values but the moment I plug in something like 543212 as input, I end up with a StackOverFlowError on line 20, followed by multiple instances of StackOverFlowErrors on line 24. Here is my code :
package nisarg;
import java.util.Scanner;
public class Chef_prime_palindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
isPalindrome(num + 1);
}
public static boolean isPrime(long num) {
long i;
for (i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void isPalindrome(long num) {
String word = Long.toString(num);
int i;
for (i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
isPalindrome(num + 1);
}
}
if (i == word.length() / 2) {
if (isPrime(num)) {
System.out.println(num);
System.exit(0);
} else {
isPalindrome(num + 1);
}
}
}
}
All shown exiting solutions use recursion and have the problem that at some point they will reach the point where a StackOverflowException will occur.
A better solution which would also be parallelizable would be to change it into a loop.
It could be something like:
package nisarg;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;
public class Chef_prime_palindromes {
private static final CopyOnWriteArrayList<BigInteger> PRIMESCACHE
= new CopyOnWriteArrayList<>();
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
BigInteger num = new BigInteger(input.nextLine());
initPrimes(num);
for (num = num.add(BigInteger.ONE);
!isPrimePalindrome(num);
num = num.add(BigInteger.ONE));
System.out.println(num.toString());
}
}
private static void initPrimes(BigInteger upTo) {
BigInteger i;
for (i = new BigInteger("2"); i.compareTo(upTo) <= 0 ; i = i.add(BigInteger.ONE)) {
isPrime(i);
}
}
public static boolean isPrimePalindrome(BigInteger num) {
return isPrime(num) && isPalindrome(num);
}
// could be optimized
public static boolean isPrime(BigInteger num) {
for (int idx = PRIMESCACHE.size() - 1; idx >= 0; --idx) {
if (num.mod(PRIMESCACHE.get(idx)).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
if (!PRIMESCACHE.contains(num)) {
PRIMESCACHE.add(num);
}
return true;
}
public static boolean isPalindrome(BigInteger num) {
String word = num.toString();
int i;
for (i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
return false;
}
}
return true;
}
}
A new String object is created in each recursive call and placed onto stack (the place where all variables created in methods are stored until you leave the method), which for a deep enough recursion makes JVM reach the end of allocated stack space.
I changed the locality of the String object by placing it into a separate method, thus reducing its locality and bounding its creation and destruction (freeing of stack space) to one recursive call.
package com.company;
import java.util.Scanner;
public class Chef_prime_palindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
isPalindrom(num + 1);
}
public static boolean isPrime(long num) {
long i;
for (i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
private static void isPalindrom(long num) {
for (; ; ) {
if (isPalindrome(num)) {
if (isPrime(num)) {
System.out.println(num);
System.exit(0);
} else {
num++;
}
} else {
num++;
}
}
}
public static boolean isPalindrome(long num) {
String string = String.valueOf(num);
return string.equals(new StringBuilder(string).reverse().toString());
}
}
First thing you should be aware of is the fact that your resources are limited. Even if your implementation was precise and all recursive calls were correct, you may still get the error. The error indicates your JVM stack ran out of space. Try to increase the size of your JVM stack ( see here for details).
Another important thing is to look for the distribution of prime and palindrome numbers. Your code runs by testing every num+1 against palindrome property. This is incorrect. You test for palindrome only when the number is prime. This will make the computation much much easier (and reduce recursive calls). I have edited your code accordingly and got the closest palindrome number after 543212 (1003001) . Here it is:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
//isPalindrome(num+1);
nextPrimePalindrome(num+1);
}
public static void nextPrimePalindrome(long num)
{
boolean flag=true;
while(flag)
{
if(isPrime(num))
if(isPalindrome(num))
{
System.out.println(num);
flag=false;
}
num++;
}
}
public static boolean isPrime(long num){
long i;
for(i=2;i<num;i++){
if(num%i == 0){
return false;
}
}
return true;
}
public static boolean isPalindrome(long num)
{
String word=Long.toString(num);
for(int i=0;i<word.length()/2;i++)
if(word.charAt(i)!=word.charAt(word.length()-i-1))
return false;
return true;
}
}

how to use recursion for converting String to int

I want to convert String input into int using recursion. This is the code I came up with but if my input is 123456 it only returns 124. If I enter 1234567, it gives an error.
import java.util.*;
public class Problem1 {
static int x =0;
static int counter = 0;
//input
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String s= scan.nextLine();
System.out.println(recursive(s));
}
//recursive method
public static int recursive(String s){
if(s.length()==1){
x=(x*10)+ Integer.parseInt(s.substring(0,1));
return x;
}
else{
x = (x*10)+Integer.parseInt(s.substring(0,1));
counter++;
return recursive(s.substring(counter,s.length()-1));
}
}
}
import java.util.Scanner;
public class Problem1 {
static int x = 0;
static int counter = 0;
// input
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println(recursive(s));
}
// recursive method
public static int recursive(String s) {
if (s.length() == 1) {
x = (x * 10) + Integer.parseInt(s.substring(0, 1));
return x;
} else {
x = (x * 10) + Integer.parseInt(s.substring(0, 1));
counter++;
return recursive(s.substring(1, s.length()));
}
}
}
Look at your static counter variable. You are incrementing it every time. But you only want to have the substring starting at 1 (so cut off the first "letter").
So instead of using:
counter++;
return recursive(s.substring(counter,s.length()-1));
consider using:
return recursive(s.substring(1)); // you even don't really need the length
Because the String s parameter is as follows:
1st call: 1234567
2nd call: 234567
3rd call: 34567
4th call: 4567
...
So, you only have to cut off the first letter.
Btw: your sample "project" is a really funny one ;)
A few notes to start:
If you're doing recursion, you probably don't want to use a member variable. It's not wrong to do so, but not really typical of the pattern (your x variable).
It's often handy to pass in state through the recursion, although you wouldn't have to (that is, current value of x).
Your case is a little odd because you have to change your current parse value for every sub-parse (shifting by 10 each time); makes it a little more complicated.
If you are going to keep x as a member variable (which does seem to make sense in this case), you don't need to return anything from recursive.
Can you really not just use Integer.parseInt()?
Code could be much more simple, something like:
void recursive (String s)
{
if (s.length() == 0) return 0;
x = x * 10 + Integer.parseInt(s.substring(0, 1));
recursive(s.substring(1));
}
recursion("1234567", 0, 1)
The above code will turn the string "1234567" into an int using recursion. You must pass the string you want to convert, and then 0 and 1.
public static int recursion(String s, int result, int place) {
result += place * Integer.parseInt(s.charAt(s.length() - 1) + "");
if(s.length() == 1) {
return result;
}
else {
return recursion(s.substring(0, s.length() - 1), result, place * 10);
}
}
public static int computeStr(String str) {
if (str.equals("")) {
return 0;
}
int x = 1;
for (int i = 0; i < str.length() - 1; i++) {
x = x * 10;
}
x = x * Integer.parseInt(str.substring(0, 1));
return x + computeStr(str.substring(1));
}
For example: "2432" is (2 * 1000) + (4 * 100) + (3*10) + (2*1) = 2432
this algorithm begins at first position (2) from 2432
I know its kind of a late response but you could try something like this :-
private static int stringToInt(String string) {
if (string.length() == 0) {
return 0;
}
int rv;
int num = string.charAt(string.length() - 1) - '0';
String restOfTheString = string.substring(0, string.length() - 1);
rv = stringToInt(restOfTheString) * 10 + num;
return rv;
}
Try something like this:
Subtracting the ASCII code of the '0' character from your character returns an integer:
public class StringRecursion {
static int counter = 0;
public static void main(String[] args) {
System.out.println(convertStringToInt("123456"));
}
public static int convertStringToInt(String input) {
if (input.length() == 1)
return input.charAt(0) - '0';
int value = convertStringToInt(input.substring(0, input.length() - 1));
counter++;
return value * 10 + input.charAt(counter) - '0';
}
}
Try it like this :
public static int conStrToInt(String str) {
if(str.length()==0)
{
return 0;
}
char cc = str.charAt(0);
String ros = str.substring(1);
int factor=1;
for(int i=0;i<str.length()-1;i++)
factor*=10;
factor=factor*(cc-'0');
return factor+conStrToInt(ros);
}

Calculating factorial of 10 .. 100 with out repeating any code?

I can do it by using a for loop but it's too long. I have to do about 10 for-loops.
System.out.println("factorial of 10");
int fact = 1;
for (int x=1;x<=10;x++) {
fact=fact*x;
System.out.println(fact);
}
System.out.println(" factorial of 20 ");
double fact1 = 1;
for (double y=1;y<=20;y++){
fact1=fact1*y;
System.out.println(fact1);
}
You can use recursive methods for computing factorials.Also Adjust the type according to you in the solution.Like BigInteger or Long
public class Factorial {
public static void main (String[] args) {
int theNum, theFact;
System.out.println("This program computes the factorial " +
"of a number.");
System.out.print("Enter a number: ");
theNum=Console.in.readInt();
theFact = fact(theNum);
System.out.println(theNum + "! = " + theFact + ".");
}
static int fact(int n) {
if (n <= 1) {
return 1;
}
else {
return n * fact(n-1);
}
}
}
You can put every calculated factorial to an array and calculate new factorial value by retrieving last element of array. But, just so you know, you can calculate up to 12! with type int because with 13!, numbers become greater than int's MAX_VALUE(2^31-1). You can use BigInteger objects as a solution.
Or if you just have to calculate those specific numbers' factorial values, you can call a recursive function which works like solution above.
Use Stirling approximation for Gamma function
You can use this equation to do the trick. It's not much of a computer language if it has no loops.
Edit: Or you can use the following code with no explicit loop anywhere (borrowed from here).
import javax.swing.Timer;
import java.awt.event.*;
import java.util.concurrent.ArrayBlockingQueue;
public class Fac {
public static int fac(final int _n) {
final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1);
final Timer timer = new Timer(0, null);
timer.addActionListener(new ActionListener() {
int result = 1;
int n = _n;
public void actionPerformed(ActionEvent e) {
result *= n;
n--;
if(n == 0) {
try {
queue.put(result);
} catch(Exception ex) {
}
timer.stop();
}
}
});
timer.start();
int result = 0;
try {
result = queue.take();
} catch(Exception ex) {
}
return result;
}
public static void main(String[] args) {
System.out.println(fac(10));
}
}

Basic recursive method - factorial

I am practicing recursion and I can't see why this method does not seem to work.
Any ideas?
public void fact()
{
fact(5);
}
public int fact(int n)
{
if(n == 1){
return 1;
}
return n * (fact(n-1));
}
}
Thanks
Your code seems to work but you are not doing anything with the returned value, put method call fact or fact(5) inside of a System.out.println and see what you get.
The recursion part is fine; you're just not using its return value, which gets discarded. Here's a complete Java application of your factorial code, slightly jazzed-up for educational purposes:
public class Factorial {
public static String fact(int n) {
if(n == 1){
return "1";
}
return n + " * " + (fact(n-1)); // what happens if you switch the order?
}
public static void main(String[] args) {
System.out.println(fact(5));
// prints "5 * 4 * 3 * 2 * 1"
}
}
A simplified version of your code:
public int fact(int n)
{
if(n == 1){
return 1;
}
return n * (fact(n-1));
}
could be just:
public int fact(int n)
{
return n == 1 ? 1 : n * fact(n - 1);
}
but your code is not wrong, this is just another style (if you are not used to ternary operator keep the way it is). I prefer use the ternary operator in these cases (observe that the code is side effect free).
Works fine. You're not assigning it to anything. Here's a test that'll prove it works.
#Test
public void testYourFactorialMethod() {
assertEquals(120, fact(5));
}
public class Recursive {
public static void main(String[] argss) {
System.out.print(fac(3));
}
public static int fac(int n) {
int value = 0;
if (n == 0) {
value = 1;
} else {
value = n * fac(n - 1);
}
return value;
}
}
// out put 6
Try something like this:
(Or maybe try this directly)
public class factorial {
private static int factorial( int n ){
if (n > 1) {
return n * (factorial(n-1));
} else {
return 1;
}
}
public static void main(String[] args) {
System.out.println(factorial(100));
}
}
static int factorial(int x) {
int result;
if (x == 1) {
return 1;
}
// Call the same method with argument x-1
result = factorial(x – 1) * x;
return result;
}
For complete example check this
http://answersz.com/factorial-program-in-java-using-recursion/
It is totaly wrong to write Fibonacci with recursive methods!!
It is an old famous example for how a good/bad Algorythm affect any project
if you write Fibonatcci recursive, for calculating 120 you need 36 year toget the result!!!!!!
public static int Fibonacci(int x)
{ // bad fibonacci recursive code
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
in dot net 4.0 there is a new type name BigInteger and you can use it to make a better function
using System;
using System.Collections.Generic;
using System.Numerics; //needs a ref. to this assembly
namespace Fibonaci
{
public class CFibonacci
{
public static int Fibonacci(int x)
{
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
public static IEnumerable<BigInteger> BigFib(Int64 toNumber)
{
BigInteger previous = 0;
BigInteger current = 1;
for (Int64 y = 1; y <= toNumber; y++)
{
var auxiliar = current;
current += previous;
previous = auxiliar;
yield return current;
}
}
}
}
and you can use it like
using System;
using System.Linq;
namespace Fibonaci
{
class Program
{
static void Main()
{
foreach (var i in CFibonacci.BigFib(10))
{
Console.WriteLine("{0}", i);
}
var num = 12000;
var fib = CFibonacci.BigFib(num).Last();
Console.WriteLine("fib({0})={1}", num, fib);
Console.WriteLine("Press a key...");
Console.ReadKey();
}
}
}
and in this case you can calculate 12000 less than a second. so
Using Recursive methos is not always a good idea
Above code imported from Vahid Nasiri blog whiche wrote in Persian

Categories