Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Core Algorithm Implementations in C: Iteration, Recursion, and Constraint Solving

Tech May 13 2

Computing the Greatest Common Divisor and Least Common Multiple

Calculate the greatest common divisor (GCD) and least common multiple (LCM) for two positive integers provided by the user.

#include <stdio.h>

int compute_gcd(int first, int second) {
    while (second != 0) {
        int remainder = first % second;
        first = second;
        second = remainder;
    }
    return first;
}

int compute_lcm(int first, int second, int gcd_val) {
    return (first / gcd_val) * second;
}

int main() {
    int val_a, val_b;
    printf("Enter two positive integers: ");
    if (scanf("%d %d", &val_a, &val_b) == 2) {
        int gcd_result = compute_gcd(val_a, val_b);
        int lcm_result = compute_lcm(val_a, val_b, gcd_result);
        printf("GCD: %d\n", gcd_result);
        printf("LCM: %d\n", lcm_result);
    }
    return 0;
}

Character Frequency Analysis in Standard Input

Parse a single line of text and categorize each character in to alphabets, whitespace, digits, or miscellaneous symbols, then output the totals.

#include <stdio.h>

int main() {
    int alpha_cnt = 0, blank_cnt = 0, digit_cnt = 0, misc_cnt = 0;
    int ch;
    printf("Input a line of text:\n");
    while ((ch = getchar()) != '\n' && ch != EOF) {
        if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
            alpha_cnt++;
        } else if (ch == ' ') {
            blank_cnt++;
        } else if (ch >= '0' && ch <= '9') {
            digit_cnt++;
        } else {
            misc_cnt++;
        }
    }
    printf("Alphabets: %d\nSpaces: %d\nDigits: %d\nOthers: %d\n",
           alpha_cnt, blank_cnt, digit_cnt, misc_cnt);
    return 0;
}

Summation of Repetitive Digit Sequences

Evaluate the sum of a sequence where each term consists of a repeated base digit. The first term contains one digit, the second contains two, and so on, up to n terms.

#include <stdio.h>

int main() {
    int base_digit, term_count;
    printf("Specify the base digit and number of terms: ");
    scanf("%d %d", &base_digit, &term_count);

    long long current_term = 0;
    long long total_sum = 0;

    for (int step = 0; step < term_count; step++) {
        current_term = current_term * 10 + base_digit;
        total_sum += current_term;
    }
    printf("Resulting series sum: %lld\n", total_sum);
    return 0;
}

Factorial Series Accumulation

Compute the cumulative sum of factorials ranging from 1! to 20!. The implementation uses a single pass to maintain computational efficiency.

#include <stdio.h>

int main() {
    long long factorial_acc = 1;
    long long series_sum = 0;

    for (int idx = 1; idx <= 20; idx++) {
        factorial_acc *= idx;
        series_sum += factorial_acc;
    }
    printf("Sum of factorials from 1! to 20!: %lld\n", series_sum);
    return 0;
}

Multi-Range Numerical Aggregation

Calculate the combined total of three mathematical progressions within a single iteration: integers from 1 to 100, squared integers from 1 to 50, and the harmonic series from 1 to 10.

#include <stdio.h>

int main() {
    double accumulation = 0.0;
    for (int idx = 1; idx <= 100; idx++) {
        accumulation += idx;
        if (idx <= 50) {
            accumulation += (double)idx * idx;
        }
        if (idx <= 10) {
            accumulation += 1.0 / idx;
        }
    }
    printf("Final accumulated value: %lf\n", accumulation);
    return 0;
}

Identifying Narcissistic Three-Digit Numbers

Scan the range from 100 to 999 to locate numbers where the sum of the cubes of their individual digits equals the original number.

#include <stdio.h>

int main() {
    for (int candidate = 100; candidate < 1000; candidate++) {
        int unit = candidate % 10;
        int tens = (candidate / 10) % 10;
        int hundreds = candidate / 100;
        int cubic_sum = unit * unit * unit + tens * tens * tens + hundreds * hundreds * hundreds;

        if (candidate == cubic_sum) {
            printf("%d\n", candidate);
        }
    }
    return 0;
}

Perfect Number Discovery within a Range

Find all integers up to 1000 that are exactly equal to the sum of their proper divisors, and display their factor breakdown.

#include <stdio.h>

int main() {
    for (int num = 2; num <= 1000; num++) {
        int divisor_sum = 0;
        for (int div = 1; div < num; div++) {
            if (num % div == 0) {
                divisor_sum += div;
            }
        }
        if (divisor_sum == num) {
            printf("%d, factors: ", num);
            for (int div = 1; div < num; div++) {
                if (num % div == 0) {
                    printf("%d ", div);
                }
            }
            printf("\n");
        }
    }
    return 0;
}

Fractional Sequence Evaluation

Determine the sum of the first twenty terms in a sequence where numerators and denominators follow a Fibonacci-like progression: 2/1, 3/2, 5/3, 8/5...

#include <stdio.h>

int main() {
    double numerator = 2.0, denominator = 1.0, running_total = 0.0;
    for (int step = 0; step < 20; step++) {
        running_total += numerator / denominator;
        double next_num = numerator + denominator;
        denominator = numerator;
        numerator = next_num;
    }
    printf("Series total after 20 terms: %lf\n", running_total);
    return 0;
}

Projectile Trajectory Distance Calculation

A ball drops from a height of 100 meters, rebounding to half its previous height after each impact. Compute the total distance traveled by the time it hits the ground for the tenth time, alongside the tenth rebound height.

#include <stdio.h>

int main() {
    double initial_height = 100.0;
    double total_distance = initial_height;
    double current_bounce = initial_height / 2.0;

    for (int impact = 2; impact <= 10; impact++) {
        total_distance += current_bounce * 2.0;
        current_bounce /= 2.0;
    }
    printf("Total distance traveled: %.2f meters\n", total_distance);
    printf("Height after 10th bounce: %.2f meters\n", current_bounce);
    return 0;
}

Reverse Sequence Problem Solving

Determine the initial quantity of items when each day exactly half of the remainder minus one is consumed, leaving only a single item by the tenth morning. An iterative backward calculation is employed.

#include <stdio.h>

int main() {
    int day10_left = 1;
    int initial_count = day10_left;
    for (int day = 9; day >= 1; day--) {
        initial_count = (initial_count + 1) * 2;
    }
    printf("Initial quantity harvested on day one: %d\n", initial_count);
    return 0;
}

Iterative Square Root Approximation

Implement Newton's method to approximate the square root of a given value. The iteration terminates once the absolute difference between consecutive estimates falls below 1e-5.

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

int main() {
    double target_val, guess_val, prev_guess;
    printf("Enter a positive number: ");
    scanf("%lf", &target_val);

    guess_val = target_val / 2.0;
    prev_guess = 0.0;

    while (fabs(guess_val - prev_guess) > 1e-5) {
        prev_guess = guess_val;
        guess_val = (prev_guess + target_val / prev_guess) / 2.0;
    }
    printf("Square root of %.2f is approximately %.5f\n", target_val, guess_val);
    return 0;
}

Symmetrical Asterisk Pattern Generation

Render a centered diamond shape composed of asterisks. The algorithm calculates spacing and star count dynamically based on the absolute distance from the central row.

#include <stdio.h>

int main() {
    const int max_lines = 7;
    const int mid = max_lines / 2;

    for (int row = 0; row < max_lines; row++) {
        int distance = abs(row - mid);
        int spaces = distance;
        int stars = max_lines - (distance * 2);

        for (int s = 0; s < spaces; s++) printf(" ");
        for (int a = 0; a < stars; a++) printf("*");
        printf("\n");
    }
    return 0;
}

Constraint-Based Match Scheduling

Resolve a combinatorial scheduling puzzle where three players from Team A must be paired uniquely with three opponents from Team B, adhering to specific exclusion rules: Player A avoids opponent X, and Player C avoids opponents X and Z.

#include <stdio.h>

int main() {
    char opp_a, opp_b, opp_c;
    char team_b[] = {'x', 'y', 'z'};

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            for (int k = 0; k < 3; k++) {
                if (i == j || j == k || i == k) continue;
                opp_a = team_b[i];
                opp_b = team_b[j];
                opp_c = team_b[k];

                if (opp_a != 'x' && opp_c != 'x' && opp_c != 'z') {
                    printf("Match schedule:\n");
                    printf("Player A faces %c\n", opp_a);
                    printf("Player B faces %c\n", opp_b);
                    printf("Player C faces %c\n", opp_c);
                }
            }
        }
    }
    return 0;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.