I can't understand this Fibonacci program flow - c#

so Im new to the world of programming and thought Id pick up a book to start learning. I bought A Players Guide to C# 3rd Edition and one of the little homework assignments it gives you has me pretty stumped. I was debugging it step by step to help me understand, but the flow of the program makes no sense to me. Here it is.
static void Main(string[] args)
{
for (int index = 1; index <= 10; index++)
{
Console.WriteLine(Fibonacci(index));
}
Console.ReadKey();
}
/// <summary>
/// Returns a number from the Fibonacci sequence, starting at 1.
/// Note that this implementation is not very optimized, and can
/// take a very long time if you're looking up large numbers.
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
static ulong Fibonacci(int number)
{
if (number == 1) { return 1; }
if (number == 2) { return 1; }
return Fibonacci(number - 1) + Fibonacci(number - 2);
}
the first two times it runs through the for loop it prints out '1' and '1' because the first time through the index is '1' making that first if statement true and the second time through the index is '2' making the second if statement true. But when it runs a 3rd time and the index turns to 3 it goes to that return statement, and if my math is right (3-1) + (3-2) equates to 3, which makes sense right. So I expect it to break from the method return 3 and write that to the Console window, but it doesnt. Instead it runs through the method again this time saying the value of the number is 2.(ok??) well at least it should stop at that 2nd if statement and reprint '1' again. Nope it ignores that line hits the return statement again. What the hell is going on? Please explain this logic.

There is a nice illustration of this kind of recursive hell.
Note that the illustration is for one iteration of your loop
And also, it is drawn for this code :
return Fibonacci(number - 2) + Fibonacci(number - 1);
as you have the reversed addition, the correct program flow would be the opposite as the one shown by the diagram below.
Image was taken here : http://composingprograms.com/pages/28-efficiency.html
I call it hell for two reasons :
Difficult to read for the developper
The first time the fibfunction is called, with parameter 6, it first calls fib(4), (the left part of the tree), then, when it's over, calls fib(5) (the right part of the tree).
Recursion can however be very useful for some case, but this school-one is absolutely not fitted for this recursion. The purpose of code is not to be read only by compilers, it is to be read by developers as well.
Inefficient
As you can see, some fib(n) are called several time with the same n.
At the end, this recursive algorithm is O(2^n), which is quite bad for this problem
Even more inefficient in a loop
Remember, the illustration is for only one iteration ! You can draw a diagram for fib(n) like this for each n.
With this method, you lose each previously calculated values, instead of reusing them to calculate the next value. This loop has then complexity O(n * 2^n)

Well, it's a not so simple example of recursion, and to makes matters worst, it's being executed inside a loop... Hardly what I would use to teach people what recursion is.
So, the point of recursion is that a function will execute itself over and over again until it's stopping condition is met (And if it's never met or doesn't even exists it will create an infinite recursion, that most of the times is not a good thing).
A classic example of recursion would be to calculate factorial (and in case you don't remember how it works, 5! = 5 * 4 * 3* 2 * 1).
So an implementation of a factorial recursive method would be something like this:
Int64 Factorial(int input)
{
if(input < 0)
{
throw new ArgumentOutOfRangeException("Input must be 0 or higher.");
}
if(input < 2)
{
return 1;
}
return input * Factorial(input - 1);
}
(0! = 1, and -3! is invalid...)
Now, let's say you call this method with the number 3:
Factorial(3) will return 3 * Factorial(3-1).
Similarly, Factorial(2) will return 2 * Factorial(2-1).
Factorial(1) will simply return 1.
Putting it all together Factorial(3) will return 3 * 2 * 1 which is 3!.
Now, in your case, The Fibonacci recursive method stopping condition is number is either 1 or 2, but it calls itself twice: Fibonacci(number - 1) + Fibonacci(number - 2);. To make matters worst it's being executed from inside a for loop, calculating the number on the Fibonacci sequences by indexes (from 1 to 10).
Let's examine what Fibonacci(3) does:
Fibonacci(3) will return Fibonacci(3-1) + Fibonacci(3-2).
Fibonacci(2) will return 1.
Fibonacci(1) will return 1.
So, Fibonacci(3) will return 1 + 1.
Let's take the next number:
Fibonacci(4) will return Fibonacci(4-1) + Fibonacci(4-2).
We already calculated that Fibonacci(3) returns 2, and we know that Fibonacci(2) will return 1, so Fibonacci(4) will return 3
(or 1+1+1 if you want to step into every call).
Similarly, Fibonacci(5) will return Fibonacci(5-1) + Fibonacci(5-2) - So it's 3 + 2 and so on (Fibonacci(6) will return 5+3, Fibonacci(7) will return 8+5).

Related

multiplicative persistence - recursion?

I'm working on this:
Write a function, persistence, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of
times you must multiply the digits in num until you reach a single
digit.
For example:
persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) == 0 // because 4 is already a one-digit number
This is what I tried:
public static int Persistence(long n)
{
List<long> listofints = new List<long>();
while (n > 0)
{
listofints.Add(n % 10);
n /= 10;
}
listofints.Reverse();
// list of a splited number
int[] arr = new int[listofints.Count];
for (int i = 0; i < listofints.Count; i++)
{
arr[i] = (int)listofints[i];
}
//list to array
int pro = 1;
for (int i = 0; i < arr.Length; i++)
{
pro *= arr[i];
}
// multiply each number
return pro;
}
I have a problem with understanding recursion - probably there is a place to use it. Can some1 give me advice not a solution, how to deal with that?
It looks like you've got the complete function to process one iteration. Now all you need to do is add the recursion. At the end of the function call Persistence again with the result of the first iteration as the parameter.
Persistence(pro);
This will recursively call your function passing the result of each iteration as the parameter to the next iteration.
Finally, you need to add some code to determine when you should stop the recursion, so you only want to call Persistence(pro) if your condition is true. This way, when your condition becomes false you'll stop the recursion.
if (some stop condition is true)
{
Persistence(pro);
}
Let me take a stab at explaining when you should consider using a recursive method.
Example of Factorial: Factorial of n is found by multiplying 1*2*3*4*..*n.
Suppose you want to find out what the factorial of a number is. For finding the answer, you can write a foreach loop that keeys multiplying a number with the next number and the next number until it reaches 0. Once you reach 0, you are done, you'll return your result.
Instead of using loops, you can use Recursion because the process at "each" step is the same. Multiply the first number with the result of the next, result of the next is found by multiplying that next number with the result of the next and so on.
5 * (result of rest)
4 * (result of rest )
3 * (result of rest)
...
1 (factorial of 0 is 1).---> Last Statement.
In this case, if we are doing recursion, we have a terminator of the sequence, the last statement where we know for a fact that factorial of 0 = 1. So, we can write this like,
FactorialOf(5) = return 5 * FactorialOf(4) = 120 (5 * 24)
FactorialOf(4) = return 4 * FactorialOf(3) = 24 (4 * 6)
FactorialOf(3) = return 3 * FactorialOf(2) = 6 (3 * 2)
FactorialOf(2) = return 2 * FactorialOf(1) = 2 (2 * 1)
FactorialOf(1) = return 1 * FactorialOf(0) = 1 (1 * 1)
FactorialOf(0) = Known -> 1.
So, it would make sense to use the same method over and over and once we get to our terminator, we stop and start going back up the tree. Each statement that called the FactorialOf would start returning numbers until it reaches all the way to the top. At the top, we will have our answer.
Your case of Persistence
It calls for recursive method as well as you are taking the result and doing the same process on it each time.
Persistence(39) (not single) = return 1 + Persistence(3 * 9 = 27) = 3
Persistence(27) (not single) = return 1 + Persistence(2 * 7 = 14) = 2
Persistence(14) (not single) = return 1 + Persistence(1 * 4 = 4) = 1
Persistence(4) (single digit) = Known -> 0 // Terminator.
At the end of the day, if you have same process performed after each calculation / processing with a termination, you can most likely find a way to use recursion for that process.
You definitely can invoke your multiplication call recursively.
You will need initial sate (0 multiplications) and keep calling your method until you reach your stop condition. Then you return the last iteration you've got up to as your result and pass it through all the way up:
int persistence(int input, int count = 0) {} // this is how I would define the method
// and this is how I see the control flowing
var result = persistence(input: 39, count: 0) {
//write a code that derives 27 out of 39
//then keep calling persistence() again, incrementing the iteration count with each invocation
return persistence(input: 27, count: 1) {
return persistence(input: 14, count: 2) {
return persistence(input: 4, count: 3) {
return 3
}
}
}
}
the above is obviously not a real code, but I'm hoping that illustrates the point well enough for you to explore it further
Designing a simple recursive solution usually involves two steps:
- Identify the trivial base case to which you can calculate the answer easily.
- Figure out how to turn a complex case to a simpler one, in a way that quickly approaches the base case.
In your problem:
- Any single-digit number has a simple solution, which is persistence = 1.
- Multiplying all digits of a number produces a smaller number, and we know that the persistence of the bigger number is greater than the persistence of the smaller number by exactly one.
That should bring you to your solution. All you need to do is understand the above and write that in C#. There are only a few modifications that you need to make in your existing code. I won't give you a ready solution as that kinda defeats the purpose of the exercise, doesn't it. If you encounter technical problems with codifying your solution into C#, you're welcome to ask another question.
public int PerRec(int n)
{
string numS = n.ToString();
if(numS.Length == 1)
return 0;
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
return PerRec(number) + 1;
}
For every recursion, you should have a stop condition(a single digit in this case).
The idea here is taking your input and convert it to string to calculate that length. If it is 1 then you return 0
Then you need to do your transformation. Take all the digits from the string representation(in this case from the char array, parse all of them, after getting the IEnumerable<int>, multiply each digit to calculate the next parameter for your recursion call.
The final result is the new recursion call + 1 (which represents the previous transformation)
You can do this step in different ways:
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
convert numS into an array of char calling ToArray()
iterate over the collection and convert each char into its integer representation and save it into an array or a list
iterate over the int list multiplying all the digits to have the next number for your recursion
Hope this helps
public static int Persistence(long n)
{
if (n < 10) // handle the trivial cases - stop condition
{
return 0;
}
long pro = 1; // int may not be big enough, use long instead
while (n > 0) // simplify the problem by one level
{
pro *= n % 10;
n /= 10;
}
return 1 + Persistence(pro); // 1 = one level solved, call the same function for the rest
}
It is the classic recursion usage. You handle the basic cases, simplify the problem by one level and then use the same function again - that is the recursion.
You can rewrite the recursion into loops if you wish, you always can.

Checking whether a number contains numbers 1 to n as factors

I am trying to solve Project Euler Challenge 5, What is the smallest possible number that is evenly divisible by all the numbers from 1 to 20.
My problem is that my isMultiple() method doesn't return true when it should.
* My Code *
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Challenge_5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(isMultiple(2520, 10)); //should return True
Console.WriteLine(smallestMultiple(20)); //should return 232792560
Console.ReadLine();
}
static int factorial(int n)
{
int product = 1;
for (int i = 1; i <= n; i++)
{
product *= i;
}
return product; //returns the factorial of n, (n * n-1 * n-2... * 1)
}
static bool isMultiple(int number, int currentFactor)
{
bool returnBool = false;
if (currentFactor == 1)
{
returnBool = true; // if all factors below largestFactor can divide into the number, returns true
}
else
{
if (number % currentFactor == 0)
{
currentFactor--;
isMultiple(number, currentFactor);
}
}
return returnBool;
}
static int smallestMultiple(int largestFactor)
{
for (int i = largestFactor; i < factorial(largestFactor); i+= largestFactor) //goes through all values from the kargestFactor to largestFactor factorial
{
if (isMultiple(i, largestFactor))
{
return i; // if current number can be evenly divided by all factors, it gets returned
}
}
return factorial(largestFactor); // if no numbers get returned, the factorial is the smallest multiple
}
}
}
I know there are much easier ways to solve this, but I want the program to be used to check the lowest multiple of the numbers from 1 to any number, not just 20.
Help would be much appreciated.
EDIT
Thanks to help, i have fixed my code by changing line 42 from
isMultiple(number, currentFactor);
to
returnBool = isMultiple(number, currentFactor);
I also fixed the problem with not getting an accurate return value for smallestMultiple(20);
by changing some of the variables to long instead of int
Your problem is you forgot to use the output of isMultiple in your recursive part
if (number % currentFactor == 0)
{
currentFactor--;
returnBool = isMultiple(number, currentFactor); //you need a to save the value here.
}
Without assigning returnBool there is no way of knowing if the inner isMultiple returned true or not.
Scott's answer is perfectly valid. Forgive me if I'm wrong, but it sounds like you're a student, so in the interest of education, I thought I'd give you some pointers for cleaning up your code.
When writing recursive functions, it's (in my opinion) usually cleaner to return the recursive call directly if possible, as well as returning base cases directly, rather than storing a value that you return at the end. (It's not always possible, in complicated cases where you have to make a recursive call, modify the return value, and then make another recursive call, but these are uncommon.)
This practice:
makes base cases very obvious increasing readability and forces you to consider all of your base cases
prevents you from forgetting to assign the return value, as you did in your original code
prevents potential bugs where you might accidentally do some erroneous additional processing that alters the result before you return it
reduces the number of nested if statements, increasing readability by reducing preceding whitespace
makes code-flow much more obvious increasing readability and ability to debug
usually results in tail-recursion which is the best for performance, nearly as performant as iterative code
caveat: nowadays most compilers' optimizers will rejigger production code to produce tail-recursive functions, but getting into the habit of writing your code with tail-recursion in the first place is good practice, especially as interpreted scripting languages (e.g. JavaScript) are taking over the world, where code optimization is less possible by nature
The other change I'd make is to remove currentFactor--; and move the subtraction into the recursive call itself. It increases readability, reduces the chance of side effects, and, in the case where you don't use tail-recursion, prevents you from altering a value that you later expect to be unaltered. In general, if you can avoid altering values passed into a function (as opposed to a procedure/void), you should.
Also, in this particular case, making this change removes up to 3 assembly instructions and possibly an additional value on the stack depending on how the optimizer handles it. In long running loops with large depths, this can make a difference*.
static bool isMultiple(int number, int currentFactor)
{
if (currentFactor == 1)
{
// if all factors below largestFactor can divide into the number, return true
return true;
}
if (number % currentFactor != 0)
{
return false;
}
return isMultiple(number, currentFactor - 1);
}
* A personal anecdote regarding deep recursive calls and performance...
A while back, I was writing a program in C++ to enumerate the best moves for all possible Connect-4 games. The maximum depth of the recursive search function was 42 and each depth had up to 7 recursive calls. Initial versions of the code had an estimated running time of 2 million years, and that was using parallelism. Those 3 additional instructions can make a HUGE difference, both for sheer number of additional instructions and the amount L1 and L2 cache misses.
This algorithm came up to my mind right now, so please anyone correct me if i'm wrong.
As composite numbers are made by multiplication of prime numbers (and prime numbers can not be generated from multiplication of any other numbers) so the number must be multiplied to all prime numbers, some numbers like 6 when they are reached our smallest number is dividable (as its already multiplied to 2 and 3), but for those that are not, multiplying by a prime number (that is obviously less than the number itself so should be in our prime list) would make our smallest dividable to that number too. so for example when we get to 4, multiplying by2` (a prime number less than 4) would be enough, 8 and 9 the same way, ...
bool IsPrime(int x)
{
if(x == 1) return false;
for(int i=2;i<=Math.Sqrt(x);i+=2)
if(x%i==0) return false;
return true;
}
int smallest = 1;
List<int> primes = new List<int>();
for(int i=1;i<=20;i++)
if(IsPrime(i))
{
smallest *= i;
primes.Add(i);
}
else if(smallest % i != 0)
for(int j=0;j<primes.Count;j++)
if((primes[j]*smallest)%i == 0)
{
smallest *= primes[j];
break;
}
Edit:
As we have list of prime numbers so the best way to find out if a number is prime or not would be:
bool IsPrime(int x)
{
if(x == 1) return false;
for(int i = 0; i< primes.Count; i++)
if(x%primes[i] == 0) return false;
return true;
}

Factorial Calculations using Recursive Method call

This code is from the book: "C# 5.0 in a Nutshell" and is a sample on LinqPad. On page 39 it says:
"This method is recursive, meaning that it calls itself. Each time the method is entered,
a new int is allocated on the stack, and each time the method exits, the int is
deallocated."
Using the literal 5 yields and answer of 120 (3 yields 6)
Can someone explain how this works? I'm a VB programmer trying to learn C# and would like to understand constructs like this. I've single stepped through it many times and can't understand what happens after x == 0 and 1 is returned. Until x equals zero, the flow of execution is easy to understand. After that, the last return statement seems to be repeatedly executed (magically) until x increments back to it's original value and then returns to the point where it was originally called and produces the aforementioned (magical) numeric result.
static void Main()
{
Console.WriteLine (Factorial(5));
}
static int Factorial (int x)
{
if (x == 0) return 1;
return x * Factorial (x-1);
}
Call Factorial(3) (which returns 3 * 2)
x doesn't == 0
return 3 * Factorial(2)
Calls Factorial(2) (which returns 2 * 1)
x doesn't == 0
return 2 * Factorial(1)
Calls Factorial(1) (which returns 1 * 1)
x doesn't == 0
return 1 * Factorial(0)
Calls Factorial(0) (which returns 1)
x == 0 so return 1
An important point is that the recursive function must have a termination condition, otherwise it would call itself infinitely (until it runs out of stack space). In your example, the if (x == 0) return 1; is the termination condition. Since the function calls itself with a parameter value of one less than it was called with, eventually it will end up calling itself with 0, and that is when the recursion ends.
This brings out a problem with this code though. If you call with a negative number, it will call itself recursively with increasingly negative numbers, will never reach 0, and you'll eventually run out of stack space. How best to handle that is probably outside the scope of your question though.
The concept of recursion is not really limited to any specific language. The idea behind it that the function calls itself.
Let's consider your example: factorial function. But for now let's put implementation aside and think of it in more abstract terms. The function consists of two elements:
i) Instruction how to calculate an element 'n'.
ii) Instruction how to calculate an initial element
So how do we calculate element n for factorial? We take n and multiply it by factorial of a previous element: n-1:
n * Factorial(n-1)
And there is only one initial item: 0. That is when n == 0 the result is 1 or in other words Factorial(0) gives 1.
The algorithm you provided contains really of these two steps
if (x == 0)
return 1; // Do this when calculating Factorial of 0
else
return x * Factorial (x-1); // Do this when calculating an element n
Ok. Now what happens when we want to calculate factorial of 4? Let's break it down to specific steps.
Factorial(4) -> 4 * Factorial(4-1) -> 4 * Factorial(3)
We invoked factorial of 4. So we multiply 4 by factorial of 4-1. To get the factorial of 4-1 we again invoke factorial function:
Factorial(3) -> 3 * Factorial(3-1) -> 3 * Factorial(2)
Now we need to calculate factorial of 2.
Factorial(2) -> 2 * Factorial(2-1) -> 2 * Factorial(1)
And of 1
Factorial(1) -> 1 * Factorial(1-1) -> 1 * Factorial(0)
Note that now we have to calculate factorial of 0. But here we have a special instruction: if the argument is 0 the result has to be 1. Let's wind back our calculations:
Factorial(0) is 1. Replace the result in the calculation for factorial of 1.
Factorial(1) -> 1 * Factorial(1-1) -> 1 * 1 which is also 1
Factorial(2) -> 2 * Factorial(1) -> 2 * 1 -> 2
Factorial(3) -> 3 * Factorial(2) -> 3 * 2 -> 6
Factorial(4) -> 4 * Factorial(3) -> 4 * 3 -> 12
You mentioned following explanation:
Each time the method is entered, a new int is allocated on the stack,
and each time the method exits, the int is deallocated.
These steps when we go inside Factorial function to calculate factorial for a previous number is when a new int has to be allocated on the stack: for factorial of 4 the number 4 goes on the stack and the algorithm calculates factorial of 3, and so on.
And when we get to the very end that is to factorial of 0 we can finally start deallocating numbers. We have factorial of 0, multiply the result by 1. Factorial of 1 is returned and 1 is deallocated. Same happens for 2, 3 and finally 4.
Hope that clarified whole concept a bit. I'm aware the explanation is extensive, but, on the other hand, it's tricky to grasp it at the beginning so I preferred to be too thorough.
It's recursive because this statement here:
return x * Factorial (x-1);
returns the result of x * the result of the call to Factorial (X-1)... It's calling itself to get the answer. It breaks out of the loop when x==0 simply by returning the value of 1.
But one thing to note, to whom does x==0 return the value? The answer is most likely the loop which is accumulating the values.
The method Factorial calls itself again, starting with 5, and decrements the argument (x-1), until the passed argument x is 0.
So the first call to Factorial passes 5, the second call 4, 3, 2, 1, 0.
And the math done is: 5*4*3*2*1 = 120.
What it is doing is calling itself repeatedly.
What's effectively happening is the following.
We enter Factorial with x equal to 5 and since we're greater than 0 we multiply our 5 with the result of calling our self (Factorial) again with 5 - 1 which is 4. Inside this recursive call we find our selves doing another recursive call with 4 - 1 which is 3. We do this repeatedly until we call Factorial with 0, where it returns 1. Then that 1 returns to the recursion which multiplies it by 2, which returns to the recursion which multiplies it by 3, and then the next by 4, and then the next by 5.
In the end you return the result of 1 * 2 * 3 * 4 * 5 which is 120.
There is one call to return for each call to Factorial. These are the recursive calls unwinding after x == 0.
I think this might be easier to see if you slightly modify your code, if only temporarily:
static int Factorial (int x)
{
if (x == 0) return 1;
else
{
int y = x * Factorial (x-1);
return y;
}
}
Thanks for all the great replies to my question. I have a both a better understanding now of this piece of code works and a realization that I need to put a more in-depth study of recursion on my TO-DO list.

Recursive loop (C#)

Can someone please explain it to me? I wrote a function to calculate the factorial of a number like this in C#:
public int factorial(int input)
{
if (input == 0 || input == 1)
return 1;
else
{
int temp = 1;
for (int i = 1; i <= input; i++)
temp = temp * i;
return temp;
}
}
But I found some C++ code (I don't really know any C++ btw) which finds a factorial using a recursive loop:
int factorial(int number) {
int temp;
if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;
}
Can someone explain to me how it works? Thanks.
Well, it uses the fact that factorial(n) is n * factorial(n - 1) with a base case of n = 1.
So for example:
factorial(5) = 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
The implementation just uses this recursive definition.
Syntactically, the C++ code is identical to the same code written in C#. Don't let the language discrepancy catch you off guard! It actually looks like C to me, given that the variable is declared at the top of the function; that's not strictly necessary in either C++ or C#. I prefer to declare variables the first time I use them, combining the declaration and initialization in one single statement, but that's merely a stylistic preference that doesn't change the function of the code.
I'll try to explain this by adding comments to each line of the code snippet:
// Declare a function named "Factorial" that accepts a single integer parameter,
// and returns an integer value.
int Factorial(int number)
{
// Declare a temporary variable of type integer
int temp;
// This is a guard clause that returns from the function immediately
// if the value of the argument is less than or equal to 1.
// In that case, it simply returns a value of 1.
// (This is important to prevent the function from recursively calling itself
// forever, producing an infinite loop!)
if(number <= 1) return 1;
// Set the value of the temp variable equal to the value of the argument
// multiplied by a recursive call to the Factorial function
temp = number * Factorial(number - 1);
// Return the value of the temporary variable
return temp;
}
Recursive calls simply mean that the function calls itself from within the same function. This works because the factorial of n is equivalent to the following statement:
n! = n * (n-1)!
One great way to understand how code works is to add it to a test project, then single-step through the code using the debugger. Visual Studio has very rich support for this in C# applications. You can watch how the function recursively calls itself, watching each line execute in sequence, and even seeing the values of the variables change as operations are performed on them.
Lets analyze this line by line:
if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;
Line 1: If the number is less than or equal to zero, we return 1. This is saying that 0! = 1 and 1! = 1
Lines 2 + 3: Otherwise we return number * factorial(number - 1). Lets look at this for 5! (here i use n! as a synonym for factorial(n) for brevity)
5!
5 * 4!
5 * 4 * 3!
5 * 4 * 3 * 2!
5 * 4 * 3 * 2 * 1!
5 * 4 * 3 * 3 * 1 // Here we don't have to expand 1! in the same way because of the condition
So the whole thing expands out. Its just using the property that
n! = n * (n - 1) * ... * 2 * 1 = n * (n - 1)!
Warning: The recursive code, as always, will suffer from a stack overflow and increased memory usage as compared to an iterative (or tail-recursive-optimized) version, so use at your own risk.
A recursive function is a function that calls itself in its body. For it be bounded, and eventually return a value, two things must happen:
It has to have a base case where it doesn't call itself again, returning a known value. This base case stops the recursion. For the factorial function, this value is 1 when the input is 0.
Its recursive applications must converge to the base case. For factorial, the recursive application calls the function with the input subtracted by 1, which will eventually converge to the base case.
A simpler way to look at this function is this (only valid for positive input):
int factorial(int input) {
return input == 0 ? 1 : input * factorial(input - 1);
}
Recursive function are function calling from the same function
eg:
Test()
{
i++;
Test();
cout<<i;
}
look at the code it will call the function again and again
Problem with recursion it will work infinitely so want to stop it by a particular condition
some change in above code now look
int i=0;
Test()
{
if(i==10) return;
i++;
Test();
cout<<i;
}
output will be 10 printed 10 times, here this line cout<<i; will execute after return

Generate number sequences with LINQ

I try to write a LINQ statement which returns me all possible combinations of numbers (I need this for a test and I was inspired by this article of Eric Lippert). The method's prototype I call looks like:
IEnumerable<Collection<int>> AllSequences( int start, int end, int size );
The rules are:
all returned collections have a length of size
number values within a collection have to increase
every number between start and end should be used
So calling the AllSequences( 1, 5, 3 ) should result in 10 collections, each of size 3:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
Now, somehow I'd really like to see a pure LINQ solution. I am able to write a non LINQ solution on my own, so please put no effort into a solution without LINQ.
My tries so far ended at a point where I have to join a number with the result of a recursive call of my method - something like:
return from i in Enumerable.Range( start, end - size + 1 )
select BuildCollection(i, AllSequences( i, end, size -1));
But I can't manage it to implement BuildCollection() on a LINQ base - or even skip this method call. Can you help me here?
Enumerable.Range(1, 12)
.Select(x => (x - 1) + 1);
Think I've got it.
IEnumerable<List<int>> AllSequences(int start, int end, int size)
{
if (size == 0)
return Enumerable.Repeat<List<int>>(new List<int>(), 1);
return from i in Enumerable.Range(start, end - size - start + 2)
from seq in AllSequences(i + 1, end, size - 1)
select new List<int>{i}.Concat(seq).ToList();
}
Something like the following should do the job, I think.
public static IEnumerable<IEnumerable<int>> AllSequences(int start, int end,
int size)
{
return size <= 0 ? new[] { new int[0] } :
from i in Enumerable.Range(start, end - size - start + 2)
from seq in AllSequences(i + 1, end, size - 1)
select Enumerable.Concat(new[] { i }, seq);
}
The key to the solution is the compound from clause, which is quite handy for dealing with nested enumerables.
Notice that I've changed the method signature slightly to IEnumerable<IEnumerable<int>>, since this is more convenient when using (pure) LINQ. You can always convert it easily to a IEnumerable<ICollection<int>> at the end if you like, however.
Let me know if the code needs any explanation, but I'm hoping the LINQ syntax makes it reasonably clear.
Edit 1: Fixed bug and improved conciseness.
Edit 2:
Because I'm bored and have nothing better to do (no, not really), I thought I'd write an extension method that compute the combinations of a given list of elements, making use of the AllSequences method.
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IList<T> source,
int num)
{
return AllSequences(0, source.Count - 1, num).Select(
seq => seq.Select(i => source[i]));
}
Perhaps not the most efficient way of computing combinations, but certainly pretty compact code!

Categories