java Simple recursion - java

So there is a recursive method (can not use any loop), that has one parameter n, and the program will print out 2^n "*", for example, if n was 2, the output is ****, and if n was 3, the output is ********.
I'm stuck with this problem because I ran into some infinite recursion issues.
First I had this: but I soon realize that n will never reach the check.
↑↑↑ That was supposed to be n+1 (even though it doesn't work)
Then I tried this:
public class test {
public static void main(String[] args) {
printPowerOfTwoStars(3);
}
public static void printPowerOfTwoStars(int n){
n = (int)Math.pow(2, n);
if(n == 0){
return;
}
else{
System.out.print("*");
printPowerOfTwoStars(n-1);
}
}
}
Ran into some infinite recursion again.
This seems like a simple program with simple logic, but I'm having trouble with the condition check, because what's being compared with n keeps changing.
How should I fix this problem?
Without using any helper method or creating any static variables.
Thank you

You need to use the fact that 2 to the power of n is just 2 to the power of n-1, doubled. Your base case is that 2 to the power of 0 is 1.
public static void printPowerOfTwoStars(int n){
if(n <= 0){
System.out.print("*");
}
else{
printPowerOfTwoStars(n-1);
printPowerOfTwoStars(n-1);
}
}

Related

Strange behavior in recursive algorithm,

I was writing a recursive algorithm to calculate Fibonacci numbers in Java as part of a programming 101 course. This is the code:
public class Fib {
public static void main(String[] args) {
Fib fib = new Fib();
}
public Fib() {
int end = 9;
long[] nums = new long[2];
printFib(0, end, nums);
}
private void printFib(int i, int end, long[] nums) {
while(i < end) {
if(i == 0 || i == 1) {
nums[i] = 1;
System.out.println("1");
} else {
long fib;
fib = 0;
fib += (nums[0] + nums[1]);
nums[0] = nums[1];
nums[1] = fib;
System.out.println(fib);
}
i++;
printFib(i, end, nums);
}
}
}
As I was stepping through the program it was working as intended until i became equal to end, the variable telling the printFib method how many Fibonacci numbers it should print out. When ì was equal to end while(i < 1) returns false as expected and the program go to the last }, now you'd(me)
expect the program to return the constructor from which I initially called the function and the program should exit, this not the case. The program goes back to the while statement and somehow evaluates to false again. Then it does the same thing again except the second time it decreases i by 1(what?!) and then proceeds to the else clause when it reaches the if statement. It then does the same thing over and over alternating the amount it subtracts from i between 1 and 2. I've asked my teacher about this and he was unable to explain it.
The program works fully like I intended if I replace the while with an if so maybe there is something about while that I don't know.
Edit
So I realize now that each time the method is called i has a different value which is stored and when the method exits and i = end the program goes back to the previous calls where i had a different value.
You implemented an iterative algorithm to calculate Fibonacci series. That's what the while loop does. There is no point in making the recursive call - printFib(i, end, nums) - at the end.
If you intended a recursive implementation, the entire while loop is not needed.
This code doesn't look right to me.
I would recommend that you not print from your method. Return a value to the main and let it print.
Your recursive method should not have a while loop in it. That's iteration - exactly what you're trying to avoid here.
Your method should have a stopping condition and a call to itself. That's not what you're doing.
Think about it like this:
/**
* Recursive Fibonnaci
* User: mduffy
* Date: 2/11/2015
* Time: 8:50 AM
* #link http://stackoverflow.com/questions/28455798/strange-behavior-in-recursive-algorithm/28455863#28455863
*/
public class Math {
private static Map<Integer, Integer> memo = new ConcurrentHashMap<Integer, Integer>();
public static void main(String [] args) {
for (String arg : args) {
int n = Integer.valueOf(arg);
System.out.println(String.format("n: %d fib(n): %d", n, fibonnaci(n)));
}
}
public static int fibonnaci(int n) {
if (n < 0) throw new IllegalArgumentException("index cannot be negative");
int value = 0;
if (memo.containsKey(n)) {
value = memo.get(n);
} else {
if (n <= 1) {
value = n;
} else {
value = fibonnaci(n-1)+fibonnaci(n-2);
}
memo.put(n, value);
}
return value;
}
}
Basicly this is happening because i would guess that you are thinking of i as an reference which will influence the basic callings of the Fibunacci method calling the sub Fibunacci method. This will finally lead way to many calls of the fibunacci method.
in my eyes the loop doesn´t make sense in your recursive way of solving it.

Sieve of Eratosthenes without arrays?

I have to write a java code for the 'sieve of eratosthenes' algorithm to print out primes up to a given max value on the console but I'm not allowed to use arrays. Our professor told us it is possible to do only with the help of loops.
So I thought a lot and googled a lot about this topic and couldn't find an answer. I dont think it's possible at all because you have store the information which digits are already crossed out somewhere.
my code until now:
public static void main(String[] args) {
int n = 100;
int mark = 2;
System.out.print("Primes from 1 to "+n+": 2, ");
for (int i = 2; i <= n; i++) {
if(i % mark != 0){
System.out.print(i+", ");
mark = i;
}
}
}
-> So, i'm not allowed to do the "i % mark != 0" command with numbers which are multiples of the numbers i already printed but how am i supposed to make that clear without an array where i can delete numbers on indexes?
BUT if there is a solution I would be glad if someone could share it with me! :)
The solution can be in other programming languages, i can translate it to java myself if its possible.
Thank you in advance and best regards
Update: Thank you very much all of you, i really appreciate your help but I don't think it can be done with the basic structures. All the algorithms i have seen yet which print out primes by using basic structures are no sieve of eratosthenes. :(
The Sieve is about remembering the primes you found already. As far as I know there is no way to do this without arrays or lists and only with loops.
I checked some of the examples at RosettaCode at random and did not find one without an array and only loops.
If you add Classes and Methods as options you can come up with a recursive design:
public class Sieve
{
private int current;
private int max;
private Sieve parent;
public Sieve(int current, int max, Sieve parent )
{
this.current = current;
this.max = max;
this.parent = parent;
}
public static void main(String[] args)
{
int n = 100;
System.out.print("Primes from 1 to " + n + ":\n");
printPrimes(n);
}
private static void printPrimes(int i)
{
new Sieve(2,i,null).start();
}
private void start()
{
if(current <2 || max <2)
{
return;
}
if(this.current > max)
{
parent.print();
return;
}
for(int i = this.current+1;current<=max+1;i++)
{
if(this.testPrime(i))
{
new Sieve(i,this.max,this).start();
return;
}
}
}
private boolean testPrime(int i)
{
if(i%this.current != 0)
{
if(this.parent == null)
{
return true;
}
else
{
return this.parent.testPrime(i);
}
}
return false;
}
private void print()
{
if(this.parent != null)
{
this.parent.print();
}
System.out.print(" "+this.current);
}
}
This removes the array but uses Objects to store the Prime (each Sieve holds one prime)
I'm taking back what I said earlier. Here it is, the "sieve" without arrays, in Haskell:
sieve limit = [n | n <- [2..limit], null [i | i <- [2..n-1], j <- [0,i..n], j==n]]
It is a forgetful sieve, and it is very very inefficient. Uses only additions, and integer comparisons. The list comprehensions in it can be re-coded as loops, in an imperative language. Or to put it differently, it moves counts like a sieve would, but without marking anything, and thus uses no arrays.
Of course whether you'd consider it a "true" sieve or not depends on what is your definition of a sieve. This one constantly recreates and abandons them. Or you could say it reimplements the rem function. Which is the same thing to say, actually, and goes to the essence of why the sieve suddenly becomes so efficient when reuse - via arrays usually - becomes possible.

How to Check Array for 3 Numbers that Add to a Specific value in JAVA?

Alright guys, I've been stuck on this problem for a while now and have not been able to get past it. This is for Java. I'd appreciate any help at this point. Here are the details: Please note, we must do this in O(n) running time. We are given an array of numbers and must go through it to determine if there are any 3 numbers that sum to a specific number. HOWEVER, we are allowed to reuse any number in the array up to 3 times because we need a total of 3 numbers. We also have to output which 3 numbers gave the sum. Returning true or false.
Below is what I've got:
Do you guys have any suggestions?
You can make a for loop inside of a for loop inside of a for loop. This is for school, so I wont give you the code, but I'll give you the pseudo.
Edit: missed the O(n) part, sorry. This way should work.
public static void main(String[] args)
{
int[] test = {1,8,2,3,11,4};
System.out.println(threeSumTo(test, 6));
}
//check if 3 numbs in an array add up to int x
public static boolean threeSumTo(int[] array, int x)
{
//loop through the array
for (int i = 0; i < array.length; i++) {
boolean result = twoSumTo(array, x - array[i], i);
if (result) {
return result;
}
}
return false;
}
private static boolean twoSumTo(int[] array, int x, int low) {
int high = array.length - 1;
while (low < high) {
if (array[low] + array[high] == x) {
return true;
}
if (array[low] + array[high] > x) {
high--;
} else {
low++;
}
}
return false;
}
}
This seems to be a variation of the 3SUM problem and should obey the same restrictions.
Computing the 3SUM problem in less than O(n^2) is still a unsvoled problem.
Did your teacher ask a trick question or is that some kind of competition?
This is called a 3 sum problem and solving this problem in O(N) is impossible till now. The best you can do is O(N^2).
Check this article out.

How to solve this summation in a recursive way

Today, my teacher asked us to implement the next expression using recursion in Java (where n is a value asked to the user):
It is possible? I can't find a proper solution for this problem, but I think I will need two recursive methods.
UPDATE
So far I have done this:
public static double sumatorio(int n){
if(n==1)
return 1;
else{
return (1 + ((n-1) * segundoSumatorio(n))) + sumatorio(n-1);
}
}
public static double segundoSumatorio(int n){
if(n==1)
return 1;
else
return 1/(double)n + segundoSumatorio(n-1);
}
It looks like it's correct, but when n=3 or greater, the result is not exact. Someone knows why?
Maybe there is an error related with losing precision.
I really appreciate any help you can provide.
Hints:
Yes. One possible solution does involve two recursive methods.
(And it is a good solution ... )
Factor the problem (and the solution) into two parts; e.g. the complete "sigma" and the embedded "sigma".
Here is your code fixed. Note how the 2nd sumatorio needs 2 parameters,
and how I don't change the second parameter while calling it recursively.
This is what your formula says and not what you implemented.
This is not a precision error, you could have figured that out
because this error sounds too big for a precision error for such
small values of n.
public class Test {
public static void main(String a[]) throws Exception {
System.out.println(sumatorio(1));
System.out.println(sumatorio(2));
System.out.println(sumatorio(3));
System.out.println(sumatorio(4));
}
public static double sumatorio(int n){
return sumatorio(n ,n);
}
public static double sumatorio(int n, int m){
if(n==1)
return 1;
else{
return (1 + ((n-1) * segundoSumatorio(m))) + sumatorio(n-1, m);
}
}
public static double segundoSumatorio(int n){
if(n==1)
return 1;
else
return 1/(double)n + segundoSumatorio(n-1);
}
}
If this task is too hard for you, try splitting it in smaller chunks. The question asks for a summation, implemented by recurse. I am confident you can do summation by implementing a loop. Something like:
int sum = 0;
for(int i = 1; i < n; i++){
sum = sum+i;
}
This will sum all numbers from 1 to (n-1).
You can convert the loop into recursion by writing a simple adding method:
int sum = 0;
int doSum(int n){
if(n <= 1){
return 1;
}
else{
return n + doSum(n - 1);
}
}
sum = doSum(n);
From here on I think you should be able to catch up.
Splitting the problem into smaller subproblems is a technique used by ALL programmers. Start small and easy, adding complexity as you go.

Printing asterisks using recursion

A method, printStars(j), is available that returns a string -- a row of j asterisks. I need to write a method that recursively prints a triangle of n rows of asterisks. The first row needs to have one *, the second have two *s, etc. No iterative loops can be used (so no while, do-while, or for).
The code to do it backwards is simple enough:
public void printTriangle(int n) {
if(n >= 1) {
printStars(n));
printTriangle(n - 1);
}
}
My code thus far for the above but reversed is below. It is incorrect as i is reset to 1 in each loop. I'm just not sure how to go about it. I can only use a one-parameter function.
public void printTriangle(int n) {
int i = 1;
if(i <= n) {
printStars(i);
printTriangle(i + 1);
}
}
Just first recur, then print the line:
public void printTriangle(int n) {
if(n > 1) {
printTriangle(n - 1);
}
System.out.println(makeStars(n));
}
So the smaller triangle is printed first, and then the longer line appended.
static int i = 1;
This will ensure that i retains its value between calls to the function.
It is initialized to 1 the first time, and any changes made to the variable will persist across calls.
EDIT: As the comment says, this isn't the right way. Daniel Fischer's solution is better.
Pass the maximum value of i as a second parameter to limit the number of lines to print i.e. the maximum value for i.
Maybe a two parameters function:
public void printTriangle(int i, int n) {
if(i <= n) {
System.out.println(printStars(i));
printTriangle(i+1, n);
}
}

Categories