Created
March 24, 2018 11:01
-
-
Save andylshort/6e8ea27a541b2200f9e8ea2b2185231c to your computer and use it in GitHub Desktop.
Maths functions and experimentation (Fibonacci, Mersenne Primes etc)
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Maths | |
{ | |
internal class Maths | |
{ | |
public static IEnumerable<long> Fibonacci(int n) | |
{ | |
for (long i = 0, previousFib = 0, currentFib = 1; i < n; i++) | |
{ | |
yield return previousFib; | |
long result = previousFib + currentFib; | |
previousFib = currentFib; | |
currentFib = result; | |
} | |
} | |
public static IEnumerable<long> Primes(int n) | |
{ | |
int val = 2; | |
for (int i = 0; i < n; ) | |
{ | |
if (IsPrime(val)) | |
{ | |
i++; | |
yield return (val++); | |
} | |
else | |
{ | |
val++; | |
} | |
} | |
} | |
public static bool IsPrime(long n) | |
{ | |
if (n < 2 || (n % 2 == 0 && n != 2)) return false; | |
if (n == 2 || n == 3) return true; | |
double sqrt = Math.Sqrt(n); | |
long limit = Convert.ToInt64(Math.Floor(sqrt)); | |
for (int i = 3; i <= limit; i++) | |
if (n % i == 0) return false; | |
return true; | |
} | |
public static IEnumerable<long> Mersennes(int n) | |
{ | |
for (int i = 0; i < n; i++) | |
yield return Convert.ToInt64(Math.Pow(2.0, i)) - 1; | |
} | |
public static List<int> Factors(int n) | |
{ | |
List<int> factors = new List<int>(); | |
for (int i = 1; i <= n; i++) | |
if (n % i == 0) factors.Add(i); | |
return factors; | |
} | |
public static IEnumerable<long> Perfects(int limit) | |
{ | |
int i = 2; | |
int found = 0; | |
while (found < limit) | |
{ | |
if (IsPerfect(i)) | |
{ | |
yield return i; | |
found++; | |
} | |
i++; | |
} | |
} | |
public static Boolean IsPerfect(int n) | |
{ | |
List<int> factors = Factors(n); | |
if (factors.Count > 2) | |
{ | |
factors.RemoveAt(factors.Count - 1); | |
int sum = factors.Aggregate((x, y) => x + y); | |
if (sum == n) return true; | |
} | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment