Guest User

Untitled

a guest
Apr 26th, 2025
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.49 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <string.h>
  5.  
  6. #define MAX_DIGITS 300
  7.  
  8. void reverse_str(char* str) {
  9.     int n = strlen(str);
  10.     for (int i = 0; i < n/2; i++) {
  11.         char temp = str[i];
  12.         str[i] = str[n - i - 1];
  13.         str[n - i - 1] = temp;
  14.     }
  15. }
  16.  
  17. void add(const char* a, const char* b, char* result) {
  18.     int carry = 0;
  19.     int i;
  20.    
  21.     for (i = 0; a[i] || b[i] || carry; i++) {
  22.         int digit_a = (a[i] && i < MAX_DIGITS) ? a[i] - '0' : 0;
  23.         int digit_b = (b[i] && i < MAX_DIGITS) ? b[i] - '0' : 0;
  24.        
  25.         int sum = digit_a + digit_b + carry;
  26.         result[i] = (sum % 10) + '0';
  27.         carry = sum / 10;
  28.        
  29.         if (i >= MAX_DIGITS - 1 && carry) {
  30.             fprintf(stderr, "Buffer overflow!\n");
  31.             exit(1);
  32.         }
  33.     }
  34.     result[i] = '\0';
  35. }
  36.  
  37. int main() {
  38.     clock_t start = clock();
  39.     const int n = 1000;
  40.    
  41.     char a[MAX_DIGITS] = "0";
  42.     char b[MAX_DIGITS] = "1";
  43.     char sum[MAX_DIGITS];
  44.  
  45.     if (n == 1) {
  46.         strcpy(b, "0");
  47.     }
  48.     else if (n == 2) {
  49.         strcpy(b, "1");
  50.     }
  51.     else {
  52.         for (int i = 3; i <= n; i++) {
  53.             add(a, b, sum);
  54.             strncpy(a, b, MAX_DIGITS);
  55.             strncpy(b, sum, MAX_DIGITS);
  56.         }
  57.     }
  58.  
  59.     reverse_str(b);
  60.    
  61.     clock_t end = clock();
  62.     printf("Time: %.3f ms\n", (double)(end - start) * 1000 / CLOCKS_PER_SEC);
  63.     printf("Result: %s\n", b);
  64.    
  65.     return 0;
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment