Recursive in java - recursion

public static void mystery(int num) {
System.out.print(num % 100);
if ((num / 100) != 0)
mystery(num / 100);
System.out.print(num % 100);
}
When I call mystery(456789), the result is 896745456789.
Why does it not stop at 89674545?

Let see for the first call. num % 100 is 89.
Your code:
print 89
.. do what ever
print 89
So it will print 89...whatever...89
It doesn't stop at 45 because it only return from the 3rd call, doesn't affect the first call.

As I guessed you wanted to reverse integer two by two digits. Well, method and logic isn't wrong but there is additional line. When number is devidedd by 100 and then it's given to recursion function, System.out.print(num % 100) is automatically done in that recursion, so printing it after recursion again causes additional numbers in answer.
public class Recursion {
public static void main(String[] args) {
mystery(456789);
}
public static void mystery(int num) {
System.out.print(num % 100);
if ((num / 100) != 0)
mystery(num / 100);
}
}

If you want the output as you specified in your question try the below code
public static void mystery(int num) {
System.out.print(num % 100);
if ((num / 100) != 0)
{
mystery(num / 100);
}
else
{
System.out.print(num);
}
}
Input: mystery(456789);
Output: 89674545

Related

Retrofit+RxJava Use Case: Continually loop on API request

I want to use Retrofit w/ RxJava to make API requests for items that are a certain distance from a given location. For illustation, this is how it might it may look for Retrofit w/o RxJava:
API api = ...
List<Item> items = new ArrayList<Item>();
int miles = 50;
do {
items = api.getItems(lon, lat, distance);
miles += 50;
} while (items.size() == 0);
Essentially, we'll keep increasing the distance until we get a response that has at least 1 item.
What's the best way to handle this kind of workflow with RxJava?
You can a combination of range, concatMap and filter for this purpose:
static Observable<Integer> getItems(int distance) {
if (distance < 500) {
return Observable.<Integer>empty().delay(500, TimeUnit.MILLISECONDS);
}
return Observable.just(1).delay(500, TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
Observable
.range(1, 20)
.map(v -> 50 * v)
.concatMap(d -> getItems(d).toList())
.doOnNext(list -> System.out.println("Got a list of " + list.size() + " items"))
.filter(list -> !list.isEmpty())
.first()
.toBlocking()
.forEach(System.out::println);
;
}

Need some support in writing factorial function using Recursion

I need to write a factorial function that takes in one input and returns the factorial of the given number. if the function is passed in to be 0 or less than 0 then the function should return 0.
I am not actually sure how to write this only using the features of PSScript version 1.0 however I just wrote this, please can someone help me.
JAVA -
public static int factorial (int n) {
if (n<0) {
return 0;
}
return (n<2) ? 1 : n *factorial(n-1);
}
I want to know if there is any I could write this so could use this to write a function in PSScript version 1.0
This is what I have done so far ;
func fac (int n) return int {
if (n<0){
return 0;
}
else
{
return (n<2) ? 1 : n *factorial(n-1);
}
}
Based on the language spec you linked to I would guess the recursive factorial function would look like this in your fictional language:
func fac (int n) returns int {
if (n == 0) {
return 1;
} else {
return n * fac(n - 1);
}
}
Maybe it should check for negative arguments too.

Issue with Recursive Methods ("missing return statement")

so I have a program that is running a bunch of different recursive methods, and I cannot get it to compile/run. The error is in this method, according to my computer:
public static int fibo(int n)
// returns the nth Fibonacci number
{
if (n==0)
{
return 0;
}
else if (n==1)
{
return 1;
}
else if (n>1)
{
return fibo(n-1) + fibo(n-2);
}
}
I have this method called correctly in my main method, so the issue is in this bit of code.
I think I can help you in this. Add return n; after your else if. Outside of the code but before the last curlicue.
The code will work as long as n ≥ 0 btw; another poster here is right in that you may want to add something to catch that error.
Make sure all possible paths have a return statement. In your code, if n < 0, there is no return statement, the compiler recognizes this, and throws the error.
public static int fibo(int n)
// returns the nth Fibonacci number
{
if (n<=0)
{
return 0;
}
else if (n==1)
{
return 1;
}
else // All other cases, i.e. n >= 1
{
return fibo(n-1) + fibo(n-2);
}
}

Fibonacci linear time recursion

Why does this work only up to n=90 or so?
Trying to calculate the 94th fibonacci number gives the incorrect result.
Same thing happens if I use the Integer class instead of Long.
import java.util.HashMap;
public class FDP {
private static HashMap<Long, Long> fib = new HashMap<Long, Long>();
private static Long calculateFib(Long n) {
if(fib.get(n)==null){
Long temp = calculateFib(n-1) + calculateFib(n-2);
fib.put(n, temp);
return temp;
}
else{
return fib.get(n);
}
}
}
public static void main(String[] args) {
fib.put(0L, 0L);
fib.put(1L, 1L);
System.out.println(calculateFib(90L)); //success
System.out.println(calculateFib(94L)); //garbage??
}
}
here is a list of the Fibonacci numbers:
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
Its an overflow.
The 94th Fibonacci number is: 19740274219868223167
Long.MAX_VALUE is:
9223372036854775807
19740274219868223167 - 9223372036854775807 > 0
You can use BigInteger to handle numbers with arbitrary length.
You reach the limitations of the type Long (64bit), use BigInteger instead

Using recursion to sum numbers

I have just been studying the concept of recursion and I thought that I would try a simple example. In the following code, I am attempting to take the numbers: 1, 2, 3, 4, 5, and add them together using recursion. I expected the result to be 15, but my code is returning 16.
What am I doing wrong?
Code:
static void Main(string[] args)
{
Console.WriteLine(Sum(5));
Console.Read();
}
static int Sum(int value)
{
if (value > 0)
{
return value + Sum(value - 1);
}
else
{
return 1;
}
}
You're returning 1 in the else clause. You should be returning 0:
else
{
return 0;
}
If the value is not greater than zero, why would you return one in the first place?
Your code executes as follows:
Sum --> 5
Sum --> 4
Sum --> 3
Sum --> 2
Sum --> 1
Sum --> 0
1 <---
2 <---
4 <---
7 <---
11 <---
16 <---
Check your base case.
Others already noted the error, and I will elaborate on recursion.
Although C# does not currently perform tail call optimization (although IL has special tail instruction), it's worth mentioning that tail recursion is generally a good thing.
Tail recursion is a special case of recursion in which the last operation of the function, the tail call, is a recursive call. Since the last call is the recursive call there is no need to preserve stack frame of the calling function and the compiler can easily use this information to generate machine instruction such that the stack doesn't grow at all. So it can basically turn recursive function into an iterative one.
Rewriting your code to support tail recursion can be done as follws:
static int Sum(int result, int value)
{
if(value == 0)
return result;
return Sum(result + 1, value - 1);
}
static int Sum(int value)
{
if (value > 0)
{
return value + Sum(value - 1);
}
else
{
return 0; //Change this.
}
}
That's because, when the value is = 0, you return 1. Then it get's added.
Sum's "else" clause should return 0.
I always prefer to put the terminating case(s) up front so they're obvious, and I have a violent near-psychopathic hatred of "if cond then return a else return b" constructs. My choice would be (making it clear that it won't work properly for negative numbers):
static unsigned int Sum(unsigned int value) {
if (value == 0)
return 0;
return value + Sum(value - 1);
}
I believe that's far more readable than a morass of braces and control flow.
The others have already answered that question, but when I work with recursion, one of the things I like to do to check that it works is to use check the base case and one additional case. I your case I would test it with 1, which would yield 2. Since this is obviously wrong you might want to check for 0 which is not going to use any recursion and so it should be obvious that the error lies in the base class.
In general recursion is easier to reason about, since you can list the limited number of things you need to check, but it does initially require a leap of faith since your intuition will be wrong. Just test the edge cases and trust the math it will never fail.
int summation(int num){
if (num==1)
return 1;
return summation(num-1)+num;
}
I'm pretty sure the problem is because you want your recursion to terminate when value == 1, and it's currently terminating when value == 0.
Your terminating expression is at issue. When value == 0 (or lower), it should return a 0 rather than 1. For sake of efficiency (which, let's admit it here, obviously isn't a concern, otherwise recursion wouldn't have been used for this task), you should terminate the recursion at value == 1 and return a literal 1 to save one unnecessary level of recursion.
using System;
using NUnit.Framework;
namespace Recursion
{
[TestFixture()]
public class Test
{
[Test()]
public void TestSum ()
{
Assert.AreEqual (Sum (new int[] { }), 0);
Assert.AreEqual (Sum (new int[] { 0 }), 0);
Assert.AreEqual (Sum (new int[] { 1 }), 1);
Assert.AreEqual (Sum (new int[] { 1, 2, 3, 4, 5 }), 15);
}
public int Sum(int[] head)
{
if (head.Length == 0) return 0;
int[] tail = new int[head.Length - 1];
for (int i = 1; i < head.Length; i++)
{
tail [i-1] = head [i];
}
return head[0] + Sum (tail);
}
}
}
It could also be written like this:
public static int sum(int n){
int total;
if(n==1){
total =1;
}else{
total = sum(n-1)+n;
}
return total;
}
Actually, I think you don't need to check case else because
public static int sum(int number){
if(number > 0){
return number + sum(--number);
}
return number; // return 0 so that's why you don't need check else condition
}
To begin at the end, a recursive Sum method looks like this:
// version 3
public static int Sum(int startRange, int endRange)
{
if (endRange > startRange)
{
return endRange + Sum(startRange, endRange - 1);
}
if (endRange < startRange)
{
return startRange + Sum(endRange, startRange - 1);
}
return endRange;
}
Hardcoding the startRange to be 0 gives us:
// version 2
public static int Sum(int range)
{
if (range > 0)
{
return range + Sum(0, range - 1);
}
if (range < 0)
{
return Sum(range, -1);
}
return range;
}
...and if you want to limit the method to positive numbers only, there's no need for a sign:
// version 1
public static unsigned int Sum(unsigned int range)
{
if (range > 0)
{
return range + Sum(0, range - 1);
}
return range;
}
I hope this helps give more of an insight into summing number ranges via recursion.
static int Sum(int[] addends)
{
if (addends.Length == 1)
{
return addends[0];
}
else
{
int tailIndex = addends.Length - 1;
var subArray = addends[0..tailIndex];
return addends[tailIndex] + Sum(subArray);
}
}
Try this code:
def sumr(n):
if n==0:
return n
return n+sumr(n-1)

Resources