The Collatz Conjecture is a mathematical conjecture that concerns a sequence defined as follows:
Start with any positive integer n.
If n is even, the next number is n / 2.
If n is odd, the next number is 3n + 1.
Repeat the process until n becomes 1.
Code
c
#include <stdio.h>
#include <stdlib.h>
// Function to calculate the Collatz Conjecture sequence
void collatzConjecture(int n) {
printf("Collatz Conjecture sequence for %d:\n", n);
printf("%d ", n);
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
printf("%d ", n);
}
printf("\n");
}
int main() {
int num;
// Ask for a starting integer
printf("Enter a positive integer: ");
if (scanf("%d", &num) != 1) {
fprintf(stderr, "Invalid input.\n");
return EXIT_FAILURE;
}
// Check if the input is a positive integer
if (num <= 0) {
fprintf(stderr, "Please enter a positive integer.\n");
return EXIT_FAILURE;
}
// Calculate the Collatz Conjecture sequence
collatzConjecture(num);
return EXIT_SUCCESS;
}
Explanation
The program starts by asking the user to input a positive integer.
It checks if the input is a valid positive integer. If not, it displays an error message and exits.
The collatzConjecture function takes the input integer n and calculates the Collatz Conjecture sequence.
Inside the collatzConjecture function, it prints the sequence by iteratively applying the Collatz Conjecture rules until n becomes 1.
Example Usage
To compile and run the program, save it to a file (e.g., collatz.c), then use the following commands:
bash
gcc collatz.c -o collatz
./collatz
When you run the program, it will ask you to enter a positive integer. For example, if you enter 10, the output will be:
code
Enter a positive integer: 10
Collatz Conjecture sequence for 10:
10 5 16 8 4 2 1
This shows the Collatz Conjecture sequence starting from 10.