Skip to content

Commit

Permalink
Merge pull request #13 from Neo-vortex/CHROE_FIX_FILENAMES
Browse files Browse the repository at this point in the history
(chore)
  • Loading branch information
Timmoth authored May 25, 2024
2 parents 549e484 + 5154d55 commit c90ec0f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 42 deletions.
42 changes: 15 additions & 27 deletions DsaDotnet/Series/Factorial.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,24 @@ namespace DsaDotnet;

public static partial class Series
{
public static ulong Fibonacci(this int input)
public static BigInteger Factorial(this int n)
{
if (input <= 1)
switch (n)
{
if (input < 0)
{
throw new ArgumentException("Cannot calculate the fibonacci of a negative number");
}
case < 0:
throw new ArgumentException("Cannot compute the factorial of a negative number");
case 0 or 1:
return 1;
default:
{
BigInteger result = 1;
for (var i = 2; i <= n; i++)
{
result *= i;
}

return (ulong)input;
return result;
}
}

var n = (uint)input;
ulong a = 0, b = 1;
for (var i = 31 - BitOperations.LeadingZeroCount(n); i >= 0; i--)
{
var c = a * ((b << 1) - a);
var d = a * a + b * b;
a = c;
b = d;
if ((n & (1 << i)) == 0)
{
continue;
}

var temp = a + b;
a = b;
b = temp;
}

return a;
}
}
42 changes: 27 additions & 15 deletions DsaDotnet/Series/Fibonacci.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,36 @@ namespace DsaDotnet;

public static partial class Series
{
public static BigInteger Factorial(this int n)
public static ulong Fibonacci(this int input)
{
switch (n)
if (input <= 1)
{
case < 0:
throw new ArgumentException("Cannot compute the factorial of a negative number");
case 0 or 1:
return 1;
default:
{
BigInteger result = 1;
for (var i = 2; i <= n; i++)
{
result *= i;
}
if (input < 0)
{
throw new ArgumentException("Cannot calculate the fibonacci of a negative number");
}

return result;
}
return (ulong)input;
}

var n = (uint)input;
ulong a = 0, b = 1;
for (var i = 31 - BitOperations.LeadingZeroCount(n); i >= 0; i--)
{
var c = a * ((b << 1) - a);
var d = a * a + b * b;
a = c;
b = d;
if ((n & (1 << i)) == 0)
{
continue;
}

var temp = a + b;
a = b;
b = temp;
}

return a;
}
}

0 comments on commit c90ec0f

Please sign in to comment.