fork(4) download
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <stdint.h>
  4. #include <stdlib.h>
  5.  
  6. int ack_recursive(int m, int n) {
  7. if (m == 0) {
  8. return n + 1;
  9. }
  10.  
  11. if (n == 0) {
  12. return ack_recursive(m - 1, 1);
  13. }
  14.  
  15. return ack_recursive(m - 1, ack_recursive(m, n - 1));
  16. }
  17.  
  18. int ack_nonrecursive(int m, int n, int *status) {
  19. int *value = NULL;
  20. size_t size = 0;
  21.  
  22. while (size >= 0) {
  23. if (m == 0) {
  24. n++;
  25. if (size-- == 0) {
  26. *status = EXIT_SUCCESS;
  27. break;
  28. }
  29. m = value[size];
  30. continue;
  31. }
  32.  
  33. if (n == 0) {
  34. m--;
  35. n = 1;
  36. continue;
  37. }
  38.  
  39. size_t index = size++;
  40. if ((size & index) == 0) {
  41. if (size >= SIZE_MAX / sizeof *value) {
  42. *status = EXIT_FAILURE;
  43. break;
  44. }
  45.  
  46. void *temp = realloc(value, (2 * size + 1) * sizeof *value);
  47. if (temp == NULL) {
  48. *status = EXIT_FAILURE;
  49. break;
  50. }
  51.  
  52. value = temp;
  53. }
  54.  
  55. value[index] = m - 1;
  56. n--;
  57. }
  58.  
  59. free(value);
  60. return n;
  61. }
  62.  
  63. int main(void) {
  64. for (int m = 0; m < 2; m++) {
  65. for (int n = 0; n < 2; n++) {
  66. int status;
  67. assert(ack_recursive(m, n) == ack_nonrecursive(m, n, &status) && status == EXIT_SUCCESS);
  68. }
  69. }
  70. }
Success #stdin #stdout 0s 2376KB
stdin
Standard input is empty
stdout
Standard output is empty