Josephus Problem in C

Published on 19 January 2025 (Updated: 19 January 2025)

Welcome to the Josephus Problem in C page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

#include <stdio.h>
#include <stdlib.h>

int josephus(int n, int k) {
    if (n == 1)
        return 1;
    else
        return (josephus(n - 1, k) + k - 1) % n + 1;
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: please input the total number of people and number of people to skip.\n");
        return 1;
    }

    char *endptr;
    int n = strtol(argv[1], &endptr, 10);
    if (*endptr != '\0' || n <= 0) {
        printf("Usage: please input the total number of people and number of people to skip.\n");
        return 1;
    }

    int k = strtol(argv[2], &endptr, 10);
    if (*endptr != '\0' || k <= 0) {
        printf("Usage: please input the total number of people and number of people to skip.\n");
        return 1;
    }

    int result = josephus(n, k);
    printf("%d\n", result);

    return 0;
}

Josephus Problem in C was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.