Roadmap › Coding Round Practice (DSA in C#) › Module: Foundations
Lessons in this course (14)

3. Number programs

Basic★ Must knowLesson 3 of 14
csharp
// Fibonacci — iterative O(n) time, O(1) space
static long Fib(int n)
{
    if (n < 2) return n;
    long a = 0, b = 1;
    for (int i = 2; i <= n; i++) (a, b) = (b, a + b);
    return b;
}

// Prime check — O(√n)
static bool IsPrime(int n)
{
    if (n < 2) return false;
    if (n % 2 == 0) return n == 2;
    for (int i = 3; i * i <= n; i += 2) if (n % i == 0) return false;
    return true;
}

// Factorial — recursive and iterative
static long Fact(int n) => n <= 1 ? 1 : n * Fact(n - 1);

// Swap without temp
int x = 5, y = 9;
(x, y) = (y, x);           // tuple swap (or x ^= y; y ^= x; x ^= y;)

// Armstrong number (153 = 1³ + 5³ + 3³)
static bool IsArmstrong(int n)
{
    var digits = n.ToString();
    return digits.Sum(d => (int)Math.Pow(d - '0', digits.Length)) == n;
}

// FizzBuzz
for (int i = 1; i <= 15; i++)
    Console.WriteLine(i % 15 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : i.ToString());

// GCD (Euclid) and LCM
static int Gcd(int a, int b) => b == 0 ? a : Gcd(b, a % b);
static int Lcm(int a, int b) => a / Gcd(a, b) * b;