Last active
February 21, 2020 03:41
-
-
Save pedrovasconcellos/02563f9c82ee5a1fc168694733833503 to your computer and use it in GitHub Desktop.
Recursion Examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| void Main() | |
| { | |
| var x = 19; | |
| var y = 7; | |
| Console.WriteLine($"Factorial of x={x}, result={Factorial(x)}.\n"); | |
| Console.WriteLine($"Multiplication of x*y={x}*{y}={Multiplication(x, y)}.\n"); | |
| Console.WriteLine($"Binary of x={x}, result={DecimalToBinary(x)}.\n"); | |
| } | |
| public long Factorial(long x) | |
| { | |
| if(x == 0 || x == 1) return 1; | |
| return x * Factorial(x-1); | |
| } | |
| public long Multiplication(long x, long y) | |
| { | |
| if(x == 0 || y == 0) return 0; | |
| return x + Multiplication(x, y-1); | |
| } | |
| public string DecimalToBinary(long x) | |
| { | |
| if(x == 0 || x == 1) return x.ToString(); | |
| return DecimalToBinary(x / 2) + (x % 2).ToString(); | |
| } | |
| //Note: Another way to program | |
| //public long Factorial(long x) => (x == 0 || x == 1) ? 1 : x * Factorial(x-1); | |
| //public long Multiplication(long x, long y) => (x == 0 || y == 0) ? 0 : Multiplication(x, y-1); | |
| //public string DecimalToBinary(long x) => x == 0 || x == 1 ? x.ToString() : DecimalToBinary(x / 2) + (x % 2).ToString(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment