Advertisement
STANAANDREY

fib dyn

Feb 15th, 2023
1,219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.01 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #define CHUNK (1 << 9)
  5.  
  6. void checkAlloc(void *p) {
  7.   if (p == NULL) {
  8.     perror("");
  9.     exit(EXIT_FAILURE);
  10.   }
  11. }
  12.  
  13. typedef struct {
  14.   int len, mem;
  15.   uint64_t *at;
  16. } DynArr;
  17.  
  18. DynArr mkArr(int ini) {
  19.   DynArr arr = {ini, ini, NULL};
  20.   if (ini) {
  21.     arr.at = calloc(sizeof(uint64_t), ini);
  22.   }
  23.   return arr;
  24. }
  25.  
  26. void addToArr(DynArr *arr, uint64_t x) {
  27.   if (arr->len == arr->mem) {
  28.     arr->mem += CHUNK;
  29.     arr->at = realloc(arr->at, sizeof(uint64_t) * arr->mem);
  30.     checkAlloc(arr->at);
  31.   }
  32.   arr->at[arr->len++] = x;
  33. }
  34.  
  35. void printArr(const DynArr *const arr) {
  36.   for (int i = 0; i < arr->len; i++) {
  37.     printf("%lu ", arr->at[i]);
  38.   }
  39.   puts("");
  40. }
  41.  
  42. int main(void) {
  43.   DynArr fib = mkArr(2);
  44.   fib.at[1] = 1;
  45.  
  46.   int term;
  47.   scanf("%d", &term);
  48.   for (int i = 2; i < term; i++) {
  49.     int newElem = fib.at[i - 2] + fib.at[i - 1];
  50.     addToArr(&fib, newElem);
  51.   }
  52.  
  53.   printArr(&fib);
  54.   free(fib.at);
  55.   return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement