Skip to content

Instantly share code, notes, and snippets.

@pedrovasconcellos
Last active February 21, 2020 03:41
Show Gist options
  • Save pedrovasconcellos/02563f9c82ee5a1fc168694733833503 to your computer and use it in GitHub Desktop.
Save pedrovasconcellos/02563f9c82ee5a1fc168694733833503 to your computer and use it in GitHub Desktop.
Recursion Examples
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