The Collatz conjecture concerns what happens when we take any positive integer n
ID: 3792395 • Letter: T
Question
The Collatz conjecture concerns what happens when we take any positive integer n and apply the following algorithm:
The conjecture states that when this algorithm is continually applied, all positive integers will eventually reach 1. For example, if n=35, the sequence is
35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1
Write a C program using the fork() system call that generates this sequence in the child process. The starting number will be provided from the command line. For example, if 8 is passed as a parameter on the command line, the child process will output 8, 4, 2, 1. Have the parent invoke the wait() call to wait for the child process to complete before exiting the program. Perform necessary error checking to ensure that a positive integer is passed on the command line. Following are some running examples, assuming the compiled program named b.out:
Besides requirements in Problem 3.21, your program should also display the process IDs of both the parent and child processes. Follow the code in Figure 3.34 (page 152) to structure your program and to print the process IDs. Capture a screenshot after running your program. A sample screenshot is provided below (the output of your program should have the same structure as in the sample screenshot).
n/2, if n is even 3 x n 1 f n is oddExplanation / Answer
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int Collatz(int num)
{
int count = 0; /*Initialize count to 0*/
if(num <= 0)
{
printf("Oops.... Collatz Sequence works only for positive integers.");
return 0;
}
while(count != 10000) /*Loop repeats for 10000 times.*/
{
if(num == 1) /*If num is 1.*/
{
printf("%i ",num);/*Print it.*/
return 0; /*Return*/
}
else if(num % 2 == 0)/*If num is even.*/
{
printf("%i ",num); /*Print it.*/
num /= 2; /*Half the number.*/
}
else /*If neither condition satifies, i.e., if num is odd.*/
{
printf("%i ",num); /*Print it.*/
num = num * 3 + 1; /*Triple the number and add 1 to it.*/
}
count++; /*Increment the count.*/
}
return 0;
}
int main(int argc, char *argv[])
{
int num, stat_loc = 0;
pid_t pid;
num = atoi(argv[1]); /*Read the value.*/
pid = fork(); /*Creating a child process*/
if(pid == -1) /*If unable to create a child, generate an error message*/
{
printf("Child Process didn't get created.");
}
else if(pid == 0) /*When running the child process.*/
{
printf("The Collatz Conjecture is: ");/*Print a prompt.*/
Collatz(num); /*Call the function to print the sequence of numbers.*/
}
else if(pid > 0) /*Make the parent process wait till the child is finished.*/
{
wait(&stat_loc);
printf(" ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.