C Programming - Beginner to Brilliance / Math & Algorithm Support

Modulus, Power, Factorials

These are foundational mathematical operations that are frequently used in both academic exercises and real-world programming scenarios such as DSA, pattern problems, number theory, and competitive coding.


🔸 Modulus Operator (%)

➗ What is Modulus?

The modulus operator % returns the remainder of a division operation.

int result = 17 % 5;  // result = 2, because 17 ÷ 5 = 3 remainder 2

🧠 Properties of Modulus:

  • Only works on integers directly.

  • Result always has the same sign as the dividend (left operand).

  • Division by zero is not allowed: a % 0 → Runtime Error

✅ Example:

#include <stdio.h>
int main() {
    int a = 20, b = 7;
    printf("a %% b = %d\\n", a % b);  // Output: 6
    return 0;
}

❗ For Floating-point Numbers:

Use fmod() from math.h

#include <stdio.h>
#include <math.h>

int main() {
    double x = 7.5, y = 2.0;
    printf("fmod(x, y) = %.2f\\n", fmod(x, y));  // Output: 1.50
    return 0;
}

🔸 Power Function

⚡ Purpose:

To raise a number x to the power y: x^y.

In C, this is done using:

#include <math.h>
double result = pow(x, y);

⚠️ Important Notes:

  • pow() always returns a double.

  • You need to link with math library using lm while compiling.

    gcc program.c -lm

✅ Example:

#include <stdio.h>
#include <math.h>

int main() {
    double base = 2.0, exponent = 4.0;
    printf("Power = %.2lf\\n", pow(base, exponent));  // Output: 16.00
    return 0;
}

🔄 Manual Integer Power Function (without math.h):

This avoids floating-point results:

int power(int base, int exp) {
    int result = 1;
    for(int i = 0; i < exp; i++) {
        result *= base;
    }
    return result;
}

🔸 Factorials

❓ What is a Factorial?

Factorial of a number n is the product of all positive integers less than or equal to n.

n!=n×(n−1)×(n−2)×⋯×1n! = n \times (n-1) \times (n-2) \times \dots \times 1

n!=n×(n−1)×(n−2)×⋯×1

  • 0! = 1 by definition.


✅ Iterative Implementation:

int factorial(int n) {
    int fact = 1;
    for(int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

✅ Recursive Implementation:

int factorial(int n) {
    if (n == 0 || n == 1)
        return 1;
    else
        return n * factorial(n - 1);
}

📌 Example Program:

#include <stdio.h>

int factorial(int n) {
    int fact = 1;
    for(int i = 1; i <= n; i++)
        fact *= i;
    return fact;
}

int main() {
    int num = 5;
    printf("Factorial of %d is %d\\n", num, factorial(num));  // Output: 120
    return 0;
}

🔐 Overflow Consideration

  • Factorials grow very fast. Even 13! exceeds int range.

  • Use long long int for bigger numbers:

long long int factorial(int n);

⚡ Bonus: Modulo with Power & Factorial (Useful in DSA)

Example: (a^b) % m or (n!) % m

These are very common in modulo arithmetic problems and require:

  • Modular exponentiation (for large b)

  • Taking mod at each multiplication step