Setting up a global variable to count recursions - java

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);
}
}

Related

How to print numbers from 1 to n using recrsion in java

public static void increase(int N){
int a = 1;
if(b <= N) {
System.out.print(a + " ");
a++;
} else {
increase(N);
}
}
I can see the problem with this approach that the int a gets initialized to 1 every time the code goes for a recursive call. Can anyone suggest the correct solution?
public static void main(String[] args) {
increase(10,1);
}
private static void increase(int N,int begin){
if(begin <= N){
System.out.print(begin+" ");
begin=begin+1;
increase(N,begin);
}
return;
}
You have to create one additional private method to count current value.
public static void increase(int N) {
increase(1, N);
}
private static void increase(int a, int N) {
if (a <= N) {
if (a > 1)
System.out.print(' ');
System.out.print(i);
increase(a + 1, N);
}
}
You can just put a outside the function:
// I don't know your class
private a = 1;
static void increase(int N){
int a = 1;
if(b <= N){
System.out.print(a+" ");
a=a+1;
}
else
{
increase(N);
}
}
static void increase(int N, int a){
if (a>N) return;
System.out.print(a+" ");
a=a+1;
increase(N,a);
}
//example call from static context print 1-100
increase(100,1);

Reverse an int using recursion

I want to reverse an int but it doesn't work. For example, 123 should return 321, but the printed number is 356.
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123, 0));
}
static int reverse2(int a, int i) {
if(a == 0) {
return 0;
} else {
i = i*10 + a%10;
System.out.println(i);
return i += reverse2(a/10, i);
}
}
}
Your code should look like this:
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123, 0));
}
static int reverse2(int a, int i) {
if(a == 0) {
return i;
} else {
i = i*10 + a%10;
System.out.println(i);
return reverse2(a/10, i);
}
}
}
You should return i when a is 0.
You shouldn't add i when you call the reverse2 function because you're adding i twice.
You are greatly complicating your recursive function for printing an integer in reverse. For one, there is no good reason for reverse2 to have two integer arguments, as you can achieve your desired results with a single argument. The trick is to access the rightmost digit with the % 10 operation then shift that digit off the number with the / 10 operation. Consider these revisions:
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123));
}
static String reverse2(int number) {
if(number == 0) {
return "";
} else {
return number % 10 + reverse2(number / 10);
}
}
}
You can do it like this. You only need to pass the value you are reversing. The math computation computes 10 to the power of the number of digits in the argument.
public static int reverse(int v) {
int reversed = 0;
if (v > 0) {
int d = (int)Math.pow(10,(int)(Math.log10(v)));
reversed = reverse(v%d) * 10 + v/d;
}
return reversed;
}
Of course, if you can pass a second argument as a scratch pad, then it can be done like so. As you tear down the original value you build up the returned value.
public static int reverse(int v, int reversed) {
if (v > 0) {
return reverse(v / 10, reversed * 10 + v % 10);
}
return reversed;
}

Java recursion to find prime factors doesn't work

I am trying to get all prime factors of a number. The for loop should work until it finds the match and it should break and jump to the next if statement which checks if number is not equal to zero.
public class Factor {
public static ArrayList <Integer> HoldNum = new ArrayList();
public static void main(String[]args){
Factor object = new Factor();
object.Factor(104);
System.out.println(HoldNum.get(0));
}
public static int Factor(int number){
int new_numb = 0;
int n=0;
for( n = 1; n < 9; n++) {
if (number % n == 0) {
HoldNum.add(n);
new_numb = number/n;
break;
}
}
System.out.println(new_numb);
if(new_numb < 0) {
HoldNum.add(new_numb);
return 1;
} else {
return Factor(new_numb);
}
}
}
There are at least three errors :
As okiharaherbst wrote, your counter is not incremented.
you start your loop at 1, so yourval % 1 always equals to 0 and new_numb is always equals to your input val, so you'll loop endlessly on 104.
new_numb will never be lesser than 0.
You asked for a recursive solution. Here you go:
public class Example {
public static void main(String[] args) {
System.out.println(factors(104));
}
public static List<Integer> factors(int number) {
return factors(number, new ArrayList<Integer>());
}
private static List<Integer> factors(int number, List<Integer> primes) {
for (int prim = 2; prim <= number; prim++) {
if (number % prim == 0) {
primes.add(prim);
return factors(number / prim, primes);
}
}
return primes;
}
}
The code is not bullet-proof, it is only a quick-and-dirty example.
Java implementation...
public class PrimeFactor {
public int divisor=2;
void printPrimeFactors(int num)
{
if(num == 1)
return;
if(num%divisor!=0)
{
while(num%divisor!=0)
++divisor;
}
if(num%divisor==0){
System.out.println(divisor);
printPrimeFactors(num/divisor);
}
}
public static void main(String[] args)
{
PrimeFactor obj = new PrimeFactor();
obj.printPrimeFactors(90);
}
}

Fibonacci Recursion in Java - No For Loops?

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);
}
}
}

Java: check if number belongs to Fibonacci sequence

I'm supposed to write a code which checks if a given number belongs to the Fibonacci sequence. After a few hours of hard work this is what i came up with:
public class TP2 {
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 <= n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 8;
System.out.println(ehFibonacci(n));
}
}
I must be doing something wrong, because it always returns "false". Any tips on how to fix this?
You continue the loop while fib2 <= n, so when you are out of the loop, fib2 is always > n, and so it returns false.
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 < n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 5;
System.out.println(ehFibonacci(n));
}
This works. I am not sure about efficiency..but this is a foolproof program,
public class isANumberFibonacci {
public static int fibonacci(int seriesLength) {
if (seriesLength == 1 || seriesLength == 2) {
return 1;
} else {
return fibonacci(seriesLength - 1) + fibonacci(seriesLength - 2);
}
}
public static void main(String args[]) {
int number = 4101;
int i = 1;
while (i > 0) {
int fibnumber = fibonacci(i);
if (fibnumber != number) {
if (fibnumber > number) {
System.out.println("Not fib");
break;
} else {
i++;
}
} else {
System.out.println("The number is fibonacci");
break;
}
}
}
}
you can also use perfect square to check whether your number is Fibonacci or not. you can find the code and some explanation at geeksforgeeks.
you can also see stackexchange for the math behind it.
I'm a beginner but this code runs perfectly fine without any issues. Checked with test cases hopefully it'll solve your query.
public static boolean checkMember(int n) {
int x = 0;
int y = 1;
int sum = 0;
boolean isTrue = true;
for (int i = 1; i <= n; i++) {
x = y;
y = sum;
sum = x + y;
if (sum == n) {
isTrue=true;
break;
} else {
isTrue=false;
}
}
return isTrue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(checkMember(n));
}

Categories