Back to Code List
c

Collatz conjecture

This is a simple implementation of the Collatz conjecture using forking with c.

   main.c

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>

int Collatz(int input) {
    if(input%2 == 0) {
        return input/2;
    } else {
        return 3*input + 1;
    }
}

int main(int argc, char* argv[])
{
	if(argc == 1) {
	    printf("Please enter a number 50-1\n\n");
	    return 1;
	}
	
	char* in = argv[1];
    int input = atoi(in);
    
	
	if(input > 50 || input < 1) {
	    printf("Please enter a number 50-1\n\n");
	    return 1;
	}
	
	int curr = input;
	
	pid_t pid;
	pid = fork();
	
	if (pid ==0) {
	    printf("Child pid: %d\n",pid);
	    while (curr > 1) {
	        printf("%d ",curr);
	        curr = Collatz(curr);
	    }
	    printf("%d \n\n",curr);
	    return 0;
	} else if (pid > 0) {
        wait(pid);
	    return 0;
	}
}