Skip to content

Instantly share code, notes, and snippets.

@jgable
Created January 27, 2012 01:33
Show Gist options
  • Save jgable/1686363 to your computer and use it in GitHub Desktop.
Save jgable/1686363 to your computer and use it in GitHub Desktop.
NumberHelpers - Fibonacci Sequence, Primes, IsPrime, Triangles and Pythagoreans
using System;
using System.Collections.Generic;
public static class NumberHelpers
{
/// <summary>
/// Returns a sequence of fibonacci numbers.
/// </summary>
/// <returns></returns>
public static IEnumerable<long> Fibonacci()
{
long n = 0, m = 1, tmp = 0;
yield return 0;
yield return 1;
while (true)
{
tmp = n + m;
n = m;
m = tmp;
yield return m;
}
}
/// <summary>
/// Returns a sequence of factors for a given number.
/// </summary>
/// <param name="num">The num.</param>
/// <returns></returns>
public static IEnumerable<long> Factors(long num)
{
for (long i = 2; i * i <= num; i++)
{
if (num % i != 0)
continue;
yield return i;
if (i != i * i)
{
yield return (num / i);
}
}
}
/// <summary>
/// Returns a sequence of prime numbers.
/// </summary>
/// <param name="num">The num to start at.</param>
/// <returns></returns>
public static IEnumerable<long> Primes(long num = 2)
{
var i = num < 2 ? 2 : num;
while (true)
{
if (IsPrime(i))
yield return i;
i++;
}
}
/// <summary>
/// A Pythagorean is a set of 3 numbers such that a &lt; b &lt; c and a^2 + b^2 = c^2
/// </summary>
/// <param name="max">The max a value.</param>
/// <returns>The sequence of pythagoreans to a given max</returns>
public static IEnumerable<Tuple<long, long, long>> Pythogoreans(long max)
{
for (long i = 1; i < max - 2; i++)
{
for (var j = i + 1; j < max - 1; j++)
{
for (var k = j + 1; k < max; k++)
{
if ((i * i) + (j * j) == k * k)
{
yield return Tuple.Create(i, j, k);
}
}
}
}
}
/// <summary>
/// A triangle is a sum of all consecutive numbers from 0; e.g. Triangle(5) = 1 + 2 + 3 + 4 + 5 = 15 ///
/// </summary>
/// <returns></returns>
public static IEnumerable<long> Triangles()
{
long i = 1;
long last = 0;
while (true)
{
yield return last + i;
last = last + i;
i++;
}
}
/// <summary>
/// Weird sequence from Euler problem 14.
/// </summary>
/// <param name="start">The start.</param>
/// <returns></returns>
public static IEnumerable<long> Euler14Sequence(long start)
{
long curr = start;
yield return curr;
while (curr != 1)
{
if (curr % 2 == 0)
{
curr /= 2;
}
else
{
curr = (3 * curr) + 1;
}
yield return curr;
}
}
public static bool IsPrime(long num)
{
for (long i = 2; i * i <= num; i++)
{
if (num % i != 0)
continue;
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment