fork(2) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int find(int n, int *pathMin)
  5. {
  6. if (n == 0) return 0; // start backtracking with path length 0
  7. pathMin[0] = n;
  8. if (n == 1) return 1; // trivial result
  9. int lenMin = n;
  10. int *path = malloc(n * sizeof n);
  11. for (int a = n; a > 1; --a) {
  12. int b = n / a;
  13. if (a < b) break; // symmetric solutions which are already tested
  14. if (a * b != n) continue;
  15. // sufficient pair (a, b) found
  16. int len = find(a - 1, path);
  17. // override lenMin if a shorter path was found
  18. if (lenMin > len) {
  19. lenMin = len;
  20. // store current shortest path (it could be final result)
  21. memcpy(pathMin + 1, path, len * sizeof *path);
  22. }
  23. }
  24. free(path);
  25. return lenMin + 1;
  26. }
  27.  
  28. void printShortestPath(int n)
  29. {
  30. if (n <= 0) {
  31. fprintf(stderr, "n should be > 0!\n");
  32. return;
  33. }
  34. int *path = malloc(n * sizeof n);
  35. int len = find(n, path);
  36. printf("Length of shortest path to %d: %d\n", n, len);
  37. printf("Path:");
  38. for (int i = 0; i < len; ++i) printf(" %d", path[i]);
  39. putchar('\n');
  40. free(path);
  41. }
  42.  
  43. int main(void)
  44. {
  45. // a brute-force test for a range of numbers:
  46. for (int n = 1; n <= 20; ++n) {
  47. printShortestPath(n);
  48. }
  49. // done
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
Length of shortest path to 1: 1
Path: 1
Length of shortest path to 2: 2
Path: 2 1
Length of shortest path to 3: 3
Path: 3 2 1
Length of shortest path to 4: 2
Path: 4 1
Length of shortest path to 5: 3
Path: 5 4 1
Length of shortest path to 6: 3
Path: 6 2 1
Length of shortest path to 7: 4
Path: 7 6 2 1
Length of shortest path to 8: 4
Path: 8 3 2 1
Length of shortest path to 9: 3
Path: 9 2 1
Length of shortest path to 10: 3
Path: 10 4 1
Length of shortest path to 11: 4
Path: 11 10 4 1
Length of shortest path to 12: 4
Path: 12 5 4 1
Length of shortest path to 13: 5
Path: 13 12 5 4 1
Length of shortest path to 14: 4
Path: 14 6 2 1
Length of shortest path to 15: 3
Path: 15 4 1
Length of shortest path to 16: 4
Path: 16 15 4 1
Length of shortest path to 17: 5
Path: 17 16 15 4 1
Length of shortest path to 18: 4
Path: 18 5 4 1
Length of shortest path to 19: 5
Path: 19 18 5 4 1
Length of shortest path to 20: 3
Path: 20 4 1