JAVA: Fibonacci Recursive and Non-Recursive Function - java

Hi there sorry for this noob question. I'm Mario and may I ask if my program is correct for recursive and non-recursive function for Fibonacci Secquence nth Value.
static int recursiveMethod(int num)
{
if (num <= 1)
return num;
return recursiveMethod(num-1) + recursiveMethod(num-2);
}
static int nonRecursiveMethod(int num) {
if (num == 0) {
return 0;
}
if (num == 1) {
return 1;
}
int first = 0;
int second = 1;
int nth = 1;
for (int i = 2; i <= num; i++) {
nth = first + second;
first = second;
second = nth;
}
return nth;
}
For summary:
Example I inputted 6 as my nth value. Then the outputs are
RECURSIVE: 8 then
NON-RECURSIVE: 1 1 2 3 5 8
Is that correct?

Calling nonRecursiveMethod will produce the same output as calling recursiveMethod. The result is correct, recursiveMethod is inefficient for big numbers, though, because it will compute results for lower numbers again and again.

yeah both the approaches are fine. What I would like to suggest here is rather than calling function for every "num" you can pre-compute and store the values(Dynamic Programming).

Related

Print 2 closest, smaller Fibonacci numbers

I am having a hard time figuring out the solution to this problem. I need to write an iterative (can't use recursion) solution to a problem in which a user inputs a number via scanner (for example, 10) and it prints 2 "previous" Fib numbers.
For the input "10" example, it would be:
5
8
As they're the "biggest" two Fib numbers prior to 10.
If the input is 13, it would print:
8
13
As 13 is a Fib number itself, it prints only 1 number prior, and then itself.
Now I know how to iteratevely find the "n-th" Fib number but I can't get my mind around a solution to run til a given number (rather than the n-th Fib number) and somehow print only the last 2 before it (or, if the given number is a Fib number by itself, count that as one too).
Now I'm aware of the formula that uses the perfect square - but unfortunately, can't use that...
Edit as it made some people confused:
I do not ask for a code, nor do I want anyone to solve this for me. I just genuinely want to understand how to approach such questions.
Edit #2:
Here's a code I wrote:
int a = 0;
int b = 1;
while (a < num) {
int temp = a;
a = a + b;
b = temp;
}
System.out.println(b);
System.out.println(a);
The problem I'm having is that if the num input is indeed a Fib num - it will work as intended, otherwise, it prints 1 prior Fib num and the next one, so for input "10" it prints 8 and 13.
Explanation
You said that you already have a method that computes the n-th Fibonacci number iterative. Since Fibonacci numbers are usually defined based on the last two Fibonacci elements, you should also already have them at hand, see the definition from Wikipedia:
The only thing you need to do is to run your iterative method until you reach the input. And then output the current memorized values for F_(n - 1) and F_(n - 2) (or F_n if equal to input).
Example
Suppose you have a Fibonacci method like (which I grabbed from the first google result)
public static long fib(int n) {
if (n <= 2) {
return (n > 0) ? 1 : 0;
}
long fib1 = 0;
long fib2 = 1;
for (int i = 1; i < n; i++) {
final long newFib = fib1 + fib2;
fib1 = fib2;
fib2 = newFib;
}
return fib2;
}
You need to modify it to accept the input and return both last Fibonacci numbers fib1 and fib2. Replace the loop to n by an infinite loop from which you break once exceeding input:
public static long[] fib(long input) {
// Special cases
if (input == 1) {
return new long[] { 1l, 1l };
}
if (input == 0) {
return new long[] { 0l };
}
if (input < 0) {
return null;
}
// Seed values
long fib1 = 0;
long fib2 = 1;
// Repeat until return
while (true) {
long newFib = fib1 + fib2;
// Reached the end
if (newFib >= input) {
// Push 'newFib' to the results
if (newFib == input) {
fib1 = fib2;
fib2 = newFib;
}
return new long[] { fib1, fib2 };
}
// Prepare next round
fib1 = fib2;
fib2 = newFib;
}
}
The method now returns at [0] the second to nearest Fibonacci and at [1] the nearest Fibonacci number to input.
You can easily adjust your own method likewise using this example.
Usage:
public static void main(String[] args) {
long[] results = fib(20L);
// Prints "8, 13"
System.out.println(results[0] + ", " + results[1]);
results = fib(21L);
// Prints "13, 21"
System.out.println(results[0] + ", " + results[1]);
}
Another example
A different view to the same problem can be obtained by using some kind of nextFib method. Then you can repeatedly pick until exceeding input. Therefore, we build some class like
public class FibonacciCalculator {
private long fib1 = 0;
private long fib2 = 1;
private int n = 0;
public long nextFib() {
// Special cases
if (n <= 2) {
long result = (n > 0) ? 1 : 0;
// Increase the index
n++;
return result;
}
// Compute current and push
long newFib = fib1 + fib2;
fib1 = fib2;
fib2 = newFib;
return newFib;
}
}
And then we just call it until we exceed input, always memorizing the last two values:
public static long[] fib(long input) {
FibonacciCalculator calc = new FibonacciCalculator();
long lastFib = 0L;
long secondToLastFib = 0L;
while (true) {
long curFib = calc.nextFib();
if (curFib > input) {
return new long[] { secondToLastFib, lastFib };
} else if (curFib == input) {
return new long[] { lastFib, curFib };
}
secondToLastFib = lastFib;
lastFib = curFib;
}
}

How to exit from a method, i.e how can i return from a function in this recursion in java?

How to exit from a method, i.e how can i return from a function in this recursion in java?
public class solution {
public static int countZerosRec(int input){
int n=0;
int k =0;
int count=0;
//Base case
if(n==0)
{
return; // How can i return the method from here, i.e how can i stop the execution of the recursive program now.
}
k=input%10;
count++;
n=input/10;
countZerosRec(n);
int myans=count;
return myans;
}
}
Please help me getting out of this method.
This is a program to count number of zeroes.
Example, 34029030 ans = 3
You can try below approach:
public class MyClass {
public static void main(String args[]) {
System.out.println("total zeroes = " + returnZeroesCount(40300));
}
public static int returnZeroesCount(int input){
if(input == 0)
return 0;
int n = input % 10;
return n == 0 ? 1 + returnZeroesCount(input / 10) : returnZeroesCount(input / 10);
}
}
How it works: Assuming your input > 0, we try to get the last digit of the number by taking the modulus by 10. If it is equal to zero, we add one to the value that we will return. And what will be the value that we would be returning? It will be the number of zeroes present in the remaining number after taking out the last digit of input.
For example, in the below case, 40300: we take out 0 in first step, so we return 1+number of zeroes in 4030. Again, it appears as if we have called our recursive function for the input 4030 now. So, we again return 1+number of zeroes in 403.
In next step, since last number is 3, we simply return 0+total number of zeroes in 40 or simply as total number of zeroes present in 40 and so on.
For ending condition, we check if the input is itself 0. If it is zero then this means that we have exhausted the input number and there are no further numbers to check for. Hence, we return zero in that case. Hope this helps.
If your main focus is to find number of zeroes in a given number , You can use this alternatively:
int numOfZeroes =0;
long example = 670880930;
String zeroCounter = String.valueOf(example);
for(int i=0; i< example.length();i++){
if(zeroCounter.charAt(i) ==0){
numOfZeroes++;
}
}
System.out.print("Num of Zeros are"+ numOfZeroes);` `
Instead of posting a code answer to your question, I'll post a few pointers to get you moving.
As #jrahhali said, as your code is, it'll not get past the return
statement inside the if block(which is an error BTW, because you have an int return
type).
I'd recommend that you move the last two lines to some calling
function(such as a main method). That way all this function will
need to do is do some basic processing and move forward.
You aren't checking k at all. As it is, your count is going to
always increment.
Hope this much is enough for you to figure things out.
int count =0;
private int getZeroCount(int num){
if(num+"".length == 1){
if(num==0){
count++;
}
return count;
}
if(num%10 == 0){
count++;
}
num /= 10;
getZeroCount();
}
Method1 :
public static int countZero1(int input) {
int count = 0;
//The loop takes the remainder for the value of the input, and if it is divided by 10, then its number of digits is 0.
// When the value of the input is less than 0, the cycle ends
while (input >0){
if (input % 10 == 0){
count ++;
}
input /= 10;
}
return count;
}
Method2 :
private static int count = 0;
public static int countZero2(int input) {
//Recursive call function
if (input % 10 == 0){
count ++;
}
input /= 10;
if (input <= 0){
return count;
}else {
return countZero2(input);
}
}

How to find greatest digit in a number using recursion?

I am trying to write a function in Java that returns the greatest digit in a number using recursion.
I have managed to do it using two parameters, the number and greater digit.
Initially the greater digit parameter accepts value as 0.
static int getGreatestDigit(int num , int greater){
if(num != 0){
if(num %10 > greater){
greater = num%10;
num = num/10;
return getGreatestDigit(num , greater);
}else{
num = num/10;
return getGreatestDigit(num , greater);
}
}
return greater;
}
I want to write same recursive function but with only one parameter that is number.
Like
int getGreatestDigit(int num){
//code
}
I am stuck at logic. How to do that?
Only the first call to getGreatestDigit(num) needs to keep track of the greater result. Each recursive call to getGreatestDigit(num) will return the greatest digit in the part of the original number that it is tasked with scanning. The very first invocation of getGreatestDigit(num) can compare the number it took with the greatest number returned from all recursive calls.
int getGreatestDigit(int num)
{
if (num == 0) return 0;
int lastNum = num % 10;
int otherDigits = num / 10;
int recursiveLastNum = getGreatestDigit(otherDigits);
return Math.Max(lastNum, recursiveLastNum);
}
static int getGreatestDigit(int num)
{
return num == 0 ? 0 :
Math.Max(num % 10, getGreatestDigit(num / 10));
}
So basically, you look at the least significant digit each time, comparing it against the maximum of the rest of the digits.
You can do this, if you use the functions stack as temporary memory to hold your interim results, i.e. what was previously stored in the greater parameter.
This changes your function to be no longer tail recursive, making it worse performance wise.
int greatestDigit(int num) {
int last = num % 10;
int rest = num / 10;
if (rest == 0) {
return last;
} else {
int candidate = greatestDigit (rest);
if (candidate > last) {
return candidate;
} else {
return last;
}
}
}
/** Pseudocode:
1. if num > 9, /10 and call getGreatestDigit on that (recursive step). Then get the current digit (undivided) and return the greater of the two
2. if num <= 9, return num
*/
int getGreatestDigit(int num){
//code
}
package Map;
import java.util.ArrayList;
public class Practice8 {
public int highestDigit(int number){
ArrayList<Integer> temp= new ArrayList<>();
StringBuilder sb= new StringBuilder();
sb.append(number);
String value= sb.toString();
for(int i=0;i<value.length();i++){
temp.add((int)value.charAt(i)-'0');
}
int max=0;
for(int x: temp){
if(x>max){
max=x;
}
}
return max;
}
public static void main(String[] args) {
Practice8 practice8= new Practice8();
System.out.println(practice8.highestDigit(379));
}
}

Java - Number of occurrences of a digit in a number without loop

Given a non-negative int n, how do i return the count of the occurrences of a digit e.g 7, so for example 717 yields 2? (no loops). Here is my code but it doesn't work well.
public int count7(int n) {
int count = 0;
if(n==7){
count++;
return count;
}
else if(n>7 && n<100)
return count7(n/10)+count7(n%10);
else if( n>100)
return count7(n/10)+count7(n%10);
else return 0;
}
Your code seems like it should be working. Not sure what you mean by "doesn't work well".
Here is an a bit cleaner/shorter version of the same solution:
int count7(int n) {
if(n == 0) return 0;
return (n%10 == 7 ? 1 : 0) + count7(n/10);
}
For the fun of it:
public static int count7( int n ) {
return Integer.toString( n )
.replaceAll( "[^7]" , "" )
.length();
}
Probably better fits to code golf ,-)
Here is a solution :
public int count(int number, int digit){
String numberToString = new Integer(number).toString();
String digitToString = new Integer(digit).toString();
return StringUtils.countMatches(numberToString,digitToString);
}
It will count for you how many digit are in number
So count(717,7) will return 2
A fast solution :
return Integer.toString(n).split("7").length-1;
When you want to look at the digits in the decimal representation of a number, it's usually reasonable to let the already available and optimized number stringification function do the job (that is Integer.toString(yournumber)). Of course there are loops behind, but there's even loops in the implementation of your recursive calls...

Any easier way of finding prime numbers than this?

is there a more efficient, cleaner/elegant way of finding prime numbers than this? The code works fine, but I just wrote what seemed most logical to me and I can't figure out any other way, but to be honest it just doesn't look nice :P. I know coding isn't the most elegant of activities.
Here's my main method:
import java.util.Scanner;
public class DisplayPrimeNumbers
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer that you'd like the system to print the prime numbers till: ");
String input1 = scan.nextLine();
int input = Integer.parseInt(input1);
PrimeGenerator prime = new PrimeGenerator(input);
for (int i = 1; i < input ; i++)
{
if(prime.isPrime())
{
System.out.println(prime.getNextPrime());
}
}
System.out.println(1);
}
}
Here's my class:
public class PrimeGenerator
{
private int number;
public PrimeGenerator(int n)
{
number = n;
}
public int getNextPrime ()
{
return number+1;
}
public boolean isPrime()
{
for(int i = 2; i < number; i++)
{
if (number % i == 0)
{
number--;
return false;
}
}
number--;
return true;
}
}
While this question has already been answered I figured I'd provide my answer anyway in the hopes that somebody may find it useful:
You seem to be primarily concerned with 2 both elegance and efficiency. I'd also like to point out that correctness is equally important. Unless you have a special requirement to treat the number 1 as prime it is no longer considered so. You should equally consider the scenario when the user enters a prime number. You should also give some thought into the boundry condition of what numbers you print. Specifically if I enter the number 7, will your users expect it to output 5,3,2,1 or 7,5,3,2,1. While my personal tendency would be towards the latter, using clear and concise messages can make either option work.
Elegance
The perceived lack of elegance in your solution is largely due to your combination of two concepts: Prime Number Testing and Prime Number Generation.
A Prime Number Test is a (quick) method to determine whether or not a single arbitrarily chosen number is prime.
A Prime Number Generator is a way of generating a sequence of prime numbers which are often consecutive.
As your program demonstrates you can generate a consecutive sequence of prime numbers by testing each number within a given range and only selecting those which are prime! Keeping this as our basic strategy for the moment, let's figure out what the code might:
From our description earlier we said that a prime number test was a method (aka function) to determine if some arbitrarily chosen number was prime. So this method should take as input a(n arbitrarily chosen) number and return wether or not the given numbe was prime (ie: true/false). Let's see how it looks:
public interface PrimeNumberTest
{
bool isPrime(int value);
}
And incorporating your prime number test
public class BruteForcePrimeNumberTester : PrimeNumberTest
{
public bool isPrime(int value)
{
bool isPrime = true;
for(int i = 2; isPrime && i < value; i++)
{
if (value % i == 0)
{
isPrime = false;
}
}
return isPrime;
}
}
Your main program is then responsible for iterating over each number and printing only thsoe which the prime number test identifies as prime.
public static void main(String[] args)
{
//Determine the range of prime numbers to print
Scanner scan = new Scanner(System.in);
System.out.print("Primes smaller than what number should be printed?: ");
int max = Integer.parseInt(scan.nextLine());
//Identify how prime numbers will be tested
PrimeNumberTest test = new BruteForcePrimeNumberTest();
//Uncomment the line below if you want to include the number 1. Favour adding it here so that you may
//use re-use your prime number test elsewhere that atually needs to know if a number is prime.
//System.out.println(1);
//Print the prime numbers
for (int i = 2; i < max ; i++)
{
if(test.isPrime(i))
{
System.out.println(i);
}
}
}
Your main program however should only be concerned with prime number generation. It doesn't really care about the semantics of how those primes are generated we just want the primes. It doesn't really matter if the primes were found via primality testing or any other algorithm. So we ask ourselves what does a prime number generator look like?
For starter primes are always whole numbers so we shouldn't be storing them inside floats, doubles or decimals. That leaves 32 and 64 bit integers. If you want to generate larger prime numbers then obviously you should use the long type but I'm just going to use int. In other languages we would also have to consider things like unsigned numbers too.
Now we need to find a way to return all of these numbers at once. Trees don't really make sense as we're going to be generating a consecutive sequence. Stacks don't make sense because consumers typically want the numbers in the order they were generated. Queues could be used as they fit the first-in-first-out rule. In fact if the end application had an asynchronous prime number generator (producer) and a separate asynchronous consumer this type would be ideal. For this example however I want something read-only. Essentially a prime number generator is an Iterable<int>.
public class PrimeNumberTestGenerator : Iterable<int>
{
private int limit;
private PrimalityTester tester;
public PrimeNumberTestGenerator(PrimalityTester tester, int limit)
{
this.tester = tester;
this.limit = limit;
}
private class PrimeNumberIterator : Iterator<int>
{
private int current;
public PrimeNumberIterator()
{
}
public bool hasNext()
{
return next < limit;
}
public int moveNext()
{
if (!hasNext())
{
throw new NoSuchElementException();
}
int result = next;
do
{
next++;
} while(hasNext() && !tester.isPrime(next));
return result;
}
public void remove()
{
throw new UnsupportedOperationExecution();
}
}
public Iterator<int> iterator()
{
return new PrimeNumberIterator();
}
}
So how do we tie them together?
public static void main(String[] args)
{
//Determine the range of prime numbers to print
Scanner scan = new Scanner(System.in);
System.out.print("Primes smaller than what number should be printed?: ");
int max = Integer.parseInt(scan.nextLine());
//Identify how prime numbers will be tested
Iterable<int> primes = new PrimeNumberTestGenerator(max, new BruteForcePrimeNumberTest());
//Print the prime numbers
foreach (int prime : primes)
{
System.out.println(prime);
}
}
Efficiency
Now the other side of your question was an efficient way of determining the prime numbers within a specified range. While a quick internet search should yield a number of different "fast" algorithms for determing a set of prime numbers that are much faste than the brute force way. One such approach is the Sieve of Atkin:
public class AtkinSieve : Iterable<int>
{
private BitSet primes;
public AtkinSieve(int limit)
{
primes = new BitSet(limit);
int root = (int)Math.sqrt(limit);
primes.set(2);
primes.set(3);
//this section can be further optimized but is the approach used by most samples
for (int x = 1; x <= root; x++)
{
for (int y = 1; y <= root; y++)
{
int number;
int remainder;
number = (4 * x * x) + (y * y);
remainder = number % 12;
if (number < limit && (remainder == 1 || remainder == 5))
{
primes.flip(number);
}
number = (3 * x * x) + (y * y);
remainder = number % 12;
if (number < limit && remainder == 7)
{
primes.flip(number);
}
if (x < y)
{
number = (3 * x * x) - (y * y);
remainder = number % 12;
if (number < limit && remainder == 11)
{
primes.flip(number);
}
}
}
}
for (int i = 5; i <= root; i++)
{
if (primes.get(i))
{
int square = i * i;
for (int j = square; j < limit; j += square)
{
primes.clear(j);
}
}
}
}
}
public class SetBitIterator : Iterator<int>
{
private BitSet bits;
private int next;
private bool isReadOnly;
public SetBitIterator(BitSet bits)
{
this.bits = bits;
next = bits.nextSetBit(0);
}
public bool hasNext()
{
return next <> -1;
}
public int moveNext()
{
int result = next;
next = bits.nextSetBit(next);
return result;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
Conveniently we can now use this prime number generator by only changing a single line in our previous main program!
Change:
//Identify how prime numbers will be tested
Iterable<int> primes = new PrimeNumberTestGenerator(max, new BruteForcePrimeNumberTest());
To:
//Identify how prime numbers will be tested
Iterable<int> primes = new AtkinSieve(max);
You can speed up your search for new primes by storing the primes that you have already found in a private collection inside the PrimeGenerator. By trying only them as potential divisors instead of your for(int i = 2; i < number; i++) loop, you will have to do much fewer divisions
You can stop the "find divisors" loop well before you reach the number: specifically, you can stop when your candidate divisor exceeds the square root of the target number. This works, because you try the candidate divisors in ascending order: if there were divisors above the square root, the result of the division would have been below the square root, so you would have already found them.
Your getNextPrime method should call isPrime internally before returning the value to the caller. Otherwise, the call of getNextPrime cannot be said to return the next prime.
First and most important thing is.... U need not to check till
i
for(int i = 2; i < number; i++)
U need to to check only untill i is less than number/2...
for(int i = 2; i < (number/2); i++)
This is how I might have written it for simplicity
public static void main(String... args) {
System.out.print("Enter an integer that you'd like the system to print the prime numbers till: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
if (input >= 2)
System.out.println(2);
OUTER: for (int i = 3; i <= input; i += 2) { // skip every even number
for (int j = 3; j * j <= i; j += 2) // stop when j <= sqrt(i)
if (i % j == 0)
continue OUTER;
System.out.println(i); // 99+% of the time will be spent here. ;)
}
}
Yeah there are. I don´t know if it´s the most efficient, but it is way more efficient then this one. Check the Miller Rabin test.
Even so, if you want to work with your Code, i could tell you, you should do it like this:
public boolean isPrime(int number)
{
// You should know, that every straight number can not be prime,so you can say i+= 2
if (number == 2)
return true;
if (number % 2 == 0)
{
return false;
}
for(int i = 3; i < number; i+=2)
{
if (number % i == 0)
{
number--;
return false;
}
--number;
return true;
}
Why would a PrimeGenerator produce numbers that are not prime? That's not elegant. Remove the isPrime()-method and rewrite the getNextPrime()-method so that it will always return a prime number.
As an improvement you can step by 6 not by 2 and do 2 checks in each step. See what I found here.
Basically, every number can be written as (6k, 6k + 1, 6k+2, 6k+3,
6k+4, or 6k+5). 6k is clearly not prime. Items 6k+2 to 6k+4 can be
written as 2(3k + 1), 3(2k+1), and 2(3k + 2) and therefore aren’t
prime as they’re divisible by 2 or 3.
So my point is the following. If we want to find numbers up to 1000 we can do the following thing.
int [] primes = new int[1000];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
index = 4;
for(int i = 12; i < 1000; i += 6) {
boolean prime1 = true;
boolean prime2 = true;
int j = 1; // No need to divide by 2, the number is odd.
while(j < index && (prime1 || prime2)) {
if (prime1 && ((i - 1) % primes[j] == 0)) {
prime1 = false;
}
if (prime2 && ((i + 1) % primes[j] == 0)) {
prime2 = false;
}
j++;
}
if (prime1) {
primes[index++] = i - 1;
}
if (prime2) {
primes[index++] = i + 1;
}
}
Try this code mate.I wrote this. This is more elegant i think :)
**import java.util.*;
public class PrimeNum{
public static void main(String args[]){
Scanner x=new Scanner(System.in);
System.out.println("Enter the number : ");
long y=x.nextLong();
long i;
for( i=2;i<y;i++){
long z=y%i;
if(z==0){
System.out.println(y+" is not a prime");
System.out.println(y+" Divide by "+i);
i=y;
}
}if(i==y) System.out.println("Number is prime");
if(y==1) System.out.println("Number 1 is not a prime");
}
}**
Based on my observations a basic approach would be to use this:
int prime(int up_limit){
int counter =0;
for(int i=1;i<=up_limit;i++)
{
if(up_limit%i==0)
counter++;
}
if(count==2){
return up_limit;
}

Categories