Determine Fibonacci Number from User Input using Recursion - java

From my homework, I need to have the user enter a number in numeric form, and convert it to the simultaneous fibonacci number from the sequence, while using recursion.
My question is how can I make the sequence through an array but not store it, so the array can be the size of the number the user entered...
Here's some starting code I have:
import java.util.Scanner;
public class ReverseUserInput1 {
//a recursive method to reverse the order of user input
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ReverseUserInput1 reverseIt = new ReverseUserInput1(); //creates new object
System.out.print("Program to convert a number to a fibonacci number,");
System.out.print(" - press Enter after each number. ");
System.out.println("- type \'0 or 1\' to finish the program.");
System.out.print(" --Enter a number: ");
int aNum = in.nextInt();
reverseIt.reverseInput(aNum); //invokes reverseInput() method
}
public static int reverseInput() {
if(aNum == 0) {
return aNum;
}
else if(aNum == 1) {
return aNum;
}
else {
reverseInput();
}
System.out.println(aNum);
}
}

Here is one method, note that this also includes the negafibonacci sequence;
private static Map<Integer, BigInteger> fibCache =
new HashMap<Integer, BigInteger>();
public static BigInteger fib(int n) {
// Uses the following identities, fib(0) = 0, fib(1) = 1 and fib(2) = 1
// All other values are calculated through recursion.
if (n > 0) {
// fib(1) and fib(2)
if (n == 1 || n == 2) {
return BigInteger.ONE;
}
synchronized (fibCache) {
if (fibCache.containsKey(n)) {
return fibCache.get(n);
}
BigInteger ret = fib(n - 2).add(fib(n - 1));
fibCache.put(n, ret);
return ret;
}
} else if (n == 0) {
// fib(0)
return BigInteger.ZERO;
}
if (n % 2 == 0) {
return fib(-n).multiply(BigInteger.ZERO.subtract(BigInteger.ONE));
}
return fib(-n);
}
public static void main(String[] args) throws Exception {
for (int x = -8; x <= 8; x++) {
System.out.println(fib(x));
}
}
Outputs
-21
13
-8
5
-3
2
-1
1
0
1
1
2
3
5
8
13
21

I was not going to post the actual algorithm (see my comment to his question earlier), but then I saw an unnecessarily complex version being posted. In contrast, I'll post the concise implementation. Note this one returns the sequence starting with 1,1,2. Another variant starts with 0,1,1,2 but is otherwise equivalent. The function assumes an input value of 1 or higher.
int fib(int n) {
if(n == 1 || n == 2) return 1;
return fib(n-2) + fib(n-1);
}
That's all.

Related

How to check if a number contains a certain digit?

I need to write a boolean method called hasEight(), which takes an int as input and returns true if the number contains the digit 8 (e.g., 18, 808).
I don't want to use the "String conversion method".
I've tried the below code, but that only checks for the last digit.
import java.util.Scanner;
public class Verificare {
public static boolean hasEight(int numarVerificat) {
int rest = numarVerificat % 10;
return rest == 8;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Introduceti numarul pentru verificare: ");
int numar = keyboard.nextInt();
Verificare.hasEight(numar);
System.out.println("Afirmatia este: " + Verificare.hasEight(numar));
keyboard.close();
}
}
If you don't want to use string conversion methods then i think this method can be used.
public bool hasEight(int number)
{
while(number > 0)
{
if(number % 10 == 8)
return true;
number=number/10;
}
return false;
}
Use the below function.
boolean hasEight(int num) {
int rem;
while (num > 0) {
rem = num % 10;
if (rem == 8)
return true;
num = num / 10;
}
return false;
}
In every iteration of the loop, last digit of the number is retrieved (remainder when divided by 10). If it is 8, true is returned. Else, number is divided by 10 (integer division so that last digit is removed) and another iteration is started. When all digits are checked (8 or not), number becomes 0 and loop stops.
public static boolean hasEight(int numarVerificat)
{
while(numarVerificat > 0)
{
if(numarVerificat % 10 == 8)
break;
numarVerificat=numarVerificat/10;
}
return (numarVerificat>0);
}

Collatz Conjecture Method - Java

I am just learning to use methods in Java. I am trying to use a method to output the number of steps it takes to get to 1 using the collatz conjecture. Can anyone help me understand better how to execute the method? This is what I have so far:
public static void main(String[] args) {
collatz();
}
public static void collatz(int n) {
n = 20;
int i = 0;
if (n == 1) {
} else if (n % 2 == 0) {
n = (n / 2);
} else {
n = (3 * n + 1);
}
i++;
System.out.println(i);
}
This won't work because "i" is only going to be changed at the end of your code and you are not using recursion or any sort of loop in your code. So, even if it did compile, it won't give the right answer.
This is the recursive way that I've done for you.
public class Cycle {
static int cycle2 (int num) {
if (num == 1) {
return 0;
} else {
if (num % 2 > 0) {
return 1 + cycle2(num * 3 + 1);
} else {
return 1 + cycle2(num / 2);
}
}
}
public static void main(String[] args) {
int num = 14;
System.out.println(cycle2(num));
}
}
As I understand it you're asking about the syntax (rather than the algorithm itself), so here's another version of the above:
public static void main(String[] args) {
// collatz has to be called with a value or it won't compile
collatz(20);
}
public static void collatz(int n) {
int i = 0;
// The following has to occur inside a loop or it'll only occur once
while (n > 1)
{
// The following is what's known as "ternary form" - if the first statement is true, it'll assign the first value. Otherwise it assigns the first value.
// For example,
// int a = (1 == 2 ? 10 : 20);
// will equal 20
n = (n % 2 == 0 ?
(n / 2) : // This value will be assigned if n is even
(3 * n + 1)); // This value will be assigned if n is odd
i++;
}
System.out.println(i);
}
I know this question was asked a long time ago and i had similar problem so this is my solution:
public class Collatz {
public static void main(String[] args) {
collatz();
}
/*If you have (int n) inside method then
when you are calling collatz() you need to have
value inside parentheses-collatz(20), or do simply like I did.
Also you need while loop! It will loop n (20) untill finaly get 1.
Otherwise your code will execute only once
and you will have as a result 1 step to complete instead of 7*/
private static void collatz() {
int n = 20;
int i = 0;
while (n != 1) {
if (n % 2 == 0) {
n = (n / 2);
} else {
n = (3 * n + 1);
}
i++;
}
System.out.println(i);
}
}

Boolean Satements

public class A4work
{
private static int fibonacci(int n) {
if (n <= 1) {
return n;
}
{
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
private static boolean isAfibonacci(int a) {
int x = 0; //sequence number
int c = 0; //number in fib sequence
while (a <= c) {
c = fibonacci(x);
x++;
}
if (a == c) {
return true;
} else {
return false;
}
}
public static void main(String[] args) //called a method signiture
{
System.out.println("The 5th Square pyramidal number is " + isAfibonacci(3));
}
}
I think I have the code right, but it keeps on returning false. I'm using it to decide if a number is in the fib sequence or not.
Thanks for the help
When you use System.out.println("The 5th Square pyramidal number is "+ isAfibonacci(3) );, a in your isAfibonacci(); method becomes 3. Now look at your code knowing that.
while(3 <= 0) //replaced a with 3 here and c with 0 for visualization
{
...
}
A non-negative, non-zero integer will never be less than or equal to 0, therefore, will always result in false.
If your input a is 5, for example, you will have:
int c = 0; //number in fib sequence
while (a <= c) { ... }
The while loop will never run since 5 <= 0 is false. So a == c will always be false for any a greater than zero.
I think you want to stop iterating when c is greater than or equal to a, so the correct condition would be
while (c < a) { ... }

Memoization with recursive method in java

I am working on a homework assignment, and I have completely exhausted myself. I'm new to programming, and this is my first programming class.
this is the problem:
Consider the following recursive function in Collatz.java, which is related to a famous unsolved problem in number theory, known as the Collatz problem or the 3n + 1 problem.
public static void collatz(int n) {
StdOut.print(n + " ");
if (n == 1) return;
if (n % 2 == 0) collatz(n / 2);
else collatz(3*n + 1);}
For example, a call to collatz(7) prints the sequence
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
as a consequence of 17 recursive calls. Write a program that takes a command-line argument N and returns the value of n < N for which the number of recursive calls for collatz(n) is maximized. Hint: use memoization. The unsolved problem is that no one knows whether the function terminates for all positive values of n (mathematical induction is no help because one of the recursive calls is for a larger value of the argument).
I have tried several things: using a for loop, trying to count the number of executions with a variable incremented each time the method executed, and hours of drudgery.
Apparently, I'm supposed to use an array somehow with the memoization. However, I don't understand how I could use an array when an array's length must be specified upon initiation.
Am I doing something completely wrong? Am I misreading the question?
Here is my code so far. It reflects an attempt at trying to create an integer array:
public class Collatz2 {
public static int collatz2(int n)
{
StdOut.print(n + " ");
if (n==1) {return 1;}
else if (n==2) {return 1;}
else if (n%2==0) {return collatz2(n/2);}
else {return collatz2(3*n+1);}
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
StdOut.println(collatz2(N));
}
}
EDIT:
I wrote a separate program
public class Count {
public static void main(String[] args) {
int count = 0;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
count++;
}
StdOut.println("count is " + count);
}
}
I then used piping: %java Collatz2 6 | java Count
and it worked just fine.
Since you are interested in the maximum sequence size and not necessarily the sequence itself, it is better to have collatz return the size of the sequence.
private static final Map<Integer,Integer> previousResults = new HashMap<>();
private static int collatz(int n) {
int result = 1;
if(previousResults.containsKey(n)) {
return previousResults.get(n);
} else {
if(n==1) result = 1;
else if(n%2==0) result += collatz(n/2);
else result += collatz(3*n + 1);
previousResults.put(n, result);
return result;
}
}
The memoization is implemented by storing sequence sizes for previous values of n in Map previousResults.
You can look for the maximum in the main function:
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int maxn=0, maxSize=0;
for(int n=N; n>0; n--) {
int size = collatz(n);
if(size>maxSize) {
maxn = n;
maxSize = size;
}
}
System.out.println(maxn + " - " + maxSize);
}
The trick here is to write a recursive method where an argument is the value you want to "memoize". For instance, here is a version of a method which will return the number of steps needed to reach 1 (it supposes that n is greater than or equal to 1, of course):
public int countSteps(final int n)
{
return doCollatz(0, n);
}
public static int doCollatz(final int nrSteps, final int n)
{
if (n == 1)
return nrSteps;
final int next = n % 2 == 0 ? n / 2 : 3 * n + 1;
return doCollatz(nrSteps + 1, next);
}
If you were to record the different steps instead, you'd pass a List<Integer> as an argument and .add() to it as you went through, etc etc.

Recursive method that prints the digits of the number line by line

I'm supposed to use a recursive method to print out the digits of a number vertically.
For example, if I were to key in 13749, the output would be:
1
3
7
4
9
How should I approach this question?? It also states that I should use the if/else method to check for the base case.. I just started learning java and I'm not really good at it :(
import java.util.Scanner;
public class test2 {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();
System.out.println();
System.out.println(numbers(n));
}
public static int numbers(int n){
int sum;
if (n == 0) {
sum = 1;
} else {
System.out.println(n%10);
sum = numbers(n / 10) + (n % 10);
}
return sum;
}
}
Here is my code in C++
Just modify it for Java. You need to show the number after you call the function that way you show the last one first... as per the answer from s.ts
void recursive(int n) {
if (n < 10)
cout << n << endl;
else
{
recursive(n / 10);
cout << n % 10 << endl;
}
}
I was asked this question today in an interview!
public class Sandbox {
static void prints(int d) {
int rem = d % 10;
if (d == 0) {
return;
} else {
prints(d / 10);
}
System.out.println(rem);
}
public static void main(String[] args) {
prints(13749);
}
}
Output:
1
3
7
4
9
You asked how to approach this, so I'll give you a tip: it would be a lot easier to build up the stack and then start printing output. It also doesn't involve manipulating strings, which is a big plus in my book. The order of operations would be:
Check for base case and return if it is
Recursive call
Print
This way when you get to the base case, you'll start printing from the tail to the head of the calls:
recursive call 1
recursive call 2
recursive call 3
.... reached base case
print 3
print 2
print 1
This way you can simply print number % 10 and make the recursive call with number / 10, the base case would be when number is 0.
class PrintDigits {
public static void main(String[] args) {
String originalNumber, reverse = "";
// Creating an Scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter a number:");
// Reading an input
originalNumber = in.nextLine();
// Calculating a length
int length = originalNumber.length();
// Reverse a given number
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + originalNumber.charAt(i);
//System.out.println("Reverse number: "+reverse);
digits(Integer.parseInt(reverse));
}
/* digits of num */
public static void digits(int number) {
if (number == 0)
System.out.println("");
else {
int mode=10;
System.out.println(+number%mode);
digits(number/mode);
}
}
}
If number consists of more than one digit print ( n / 10 )
print ( n % 10 )
If you want them printed in the other order
print ( n % 10 )
If number consists of more than one digit print ( n / 10 )
try this
public class Digits {
public static void main(String[] args) {
printDigits(13749);
}
private static void printDigits(Integer number) {
int[] m = new int[number.toString().toCharArray().length];
digits(number, 0, m, 0);
for (int i= m.length - 1; i>=0; i--) {
System.out.println(m[i]);
}
}
public static int digits(int number, int reversenumber, int[] m, int i) {
if (number <= 0) {
return reversenumber;
}
m[i] = (number % 10);
reversenumber = reversenumber * 10 + (number % 10);
return digits(number/10, reversenumber, m, ++i);
}
}
Python example
def printNoVertically(number):
if number < 9:
print(number)
return
else:
printNoVertically(number/10)
print(number % 10)

Categories

Resources