You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
2.2 KiB
66 lines
2.2 KiB
#include <unistd.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include <stdint.h>
|
|
|
|
unsigned long int fib(unsigned long int n) {
|
|
if (n <= 1) return n;
|
|
return fib(n - 1) + fib(n - 2);
|
|
}
|
|
|
|
int main() {
|
|
char buffer[1024]; // Buffer to store input data
|
|
|
|
ssize_t bytes_read = read(0, buffer, sizeof(buffer) - 1);
|
|
if (bytes_read < 0) {
|
|
perror("Error reading input");
|
|
return 1;
|
|
}
|
|
buffer[bytes_read] = '\0'; // Null-terminate the string
|
|
|
|
// Parse the expected data length from the first 4 bytes for the first number
|
|
if (bytes_read < 4) {
|
|
fprintf(stderr, "Input is too short to contain valid data length.\n");
|
|
return 1;
|
|
}
|
|
|
|
// First number length and number
|
|
uint32_t first_num_length;
|
|
memcpy(&first_num_length, buffer, sizeof(uint32_t));
|
|
char *first_num_start = buffer + 4;
|
|
if (bytes_read < 4 + first_num_length + 4) { // Check if there is enough data for the first number and the second length
|
|
fprintf(stderr, "Input does not contain enough data for the first number and the second length.\n");
|
|
return 1;
|
|
}
|
|
|
|
// Second number length and number
|
|
uint32_t second_num_length;
|
|
memcpy(&second_num_length, first_num_start + first_num_length, sizeof(uint32_t));
|
|
char *second_num_start = first_num_start + first_num_length + 4;
|
|
if (bytes_read < 4 + first_num_length + 4 + second_num_length) { // Check if there is enough data for the second number
|
|
fprintf(stderr, "Input does not contain enough data for the second number.\n");
|
|
return 1;
|
|
}
|
|
|
|
// Read and calculate Fibonacci numbers
|
|
unsigned long int num1, num2;
|
|
if (sscanf(first_num_start, "%lu", &num1) != 1 || sscanf(second_num_start, "%lu", &num2) != 1) {
|
|
fprintf(stderr, "Failed to parse the numbers correctly.\n");
|
|
return 1;
|
|
}
|
|
|
|
unsigned long int fib1 = fib(num1);
|
|
unsigned long int fib2 = fib(num2);
|
|
unsigned long int sum = fib1 + fib2;
|
|
|
|
// Prepare output string
|
|
char output[1024];
|
|
int len = snprintf(output, sizeof(output), "Fibonacci(%lu) + Fibonacci(%lu) = %lu + %lu = %lu\n", num1, num2, fib1, fib2, sum);
|
|
|
|
// Write to stdout
|
|
write(1, output, len);
|
|
|
|
return 0;
|
|
}
|