fork download
  1. // 1. Library
  2. #include <stdio.h>
  3.  
  4. // 2. Definitions
  5. // (None needed for this problem)
  6.  
  7. // 3. Prototypes
  8. void getInput(int *n);
  9. int validateInput(int n);
  10. void solveNuggets(int n);
  11. void printSolution(int boxes6, int boxes9, int boxes20);
  12. void printImpossible(int n);
  13. int findClosestPossible(int n);
  14.  
  15. // 4. Main
  16. int main() {
  17. // 4.1 Variable declarations
  18. int n;
  19.  
  20. // 4.2 Calls to functions
  21. while (1) {
  22. getInput(&n);
  23. if (validateInput(n)) {
  24. solveNuggets(n);
  25. break;
  26. }
  27. }
  28. return 0;
  29. }
  30.  
  31. // 5. Functions
  32. void getInput(int *n) {
  33. printf("Sisesta nuggetite arv (N): ");
  34. scanf("%d", n);
  35. }
  36.  
  37. int validateInput(int n) {
  38. if (n <= 0) {
  39. printf("Palun sisesta positiivne arv.\n");
  40. return 0; // Return 0 (false) for invalid input
  41. }
  42. return 1; // Return 1 (true) for valid input
  43. }
  44.  
  45. void solveNuggets(int n) {
  46. int boxes6, boxes9, boxes20;
  47. int foundSolution = 0;
  48.  
  49. for (boxes20 = n / 20; boxes20 >= 0; boxes20--) {
  50. for (boxes9 = (n - boxes20 * 20) / 9; boxes9 >= 0; boxes9--) {
  51. boxes6 = (n - boxes20 * 20 - boxes9 * 9) / 6;
  52. if (boxes6 * 6 + boxes9 * 9 + boxes20 * 20 == n) {
  53. foundSolution = 1;
  54. printSolution(boxes6, boxes9, boxes20);
  55. return;
  56. }
  57. }
  58. }
  59.  
  60. if (!foundSolution) {
  61. int closest = findClosestPossible(n);
  62. printf("Unfortunately, we cannot give %d nuggets, however we can offer you %d:\n", n, closest);
  63. solveNuggets(closest);
  64. }
  65. }
  66.  
  67. void printSolution(int boxes6, int boxes9, int boxes20) {
  68. printf("6x Box: %d\n9x Box: %d\n20x Box: %d\n", boxes6, boxes9, boxes20);
  69. }
  70.  
  71. void printImpossible(int n) {
  72. printf("Ei ole võimalik anda %d tükki.\n", n);
  73. }
  74.  
  75. int findClosestPossible(int n) {
  76. int closest = n + 1;
  77. while (1) {
  78. int boxes6, boxes9, boxes20;
  79. for (boxes20 = closest / 20; boxes20 >= 0; boxes20--) {
  80. for (boxes9 = (closest - boxes20 * 20) / 9; boxes9 >= 0; boxes9--) {
  81. boxes6 = (closest - boxes20 * 20 - boxes9 * 9) / 6;
  82. if (boxes6 * 6 + boxes9 * 9 + boxes20 * 20 == closest) {
  83. return closest;
  84. }
  85. }
  86. }
  87. closest++;
  88. }
  89. }
Success #stdin #stdout 0s 5328KB
stdin
45
stdout
Sisesta nuggetite arv (N): 6x Box: 0
9x Box: 5
20x Box: 0