Advertisement
Guest User

odd_sum

a guest
Sep 22nd, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. /* Search for `count' distinct odd numbers that
  4. * are smaller than `bound' and add up to `sum'.
  5. *
  6. * Return value:
  7. * 1: A solution is found and printed.
  8. * 0: No solution was found.
  9. */
  10.  
  11. int odd_sum(int count, int bound, int sum)
  12. {
  13. // Initialize the lower bound , the next odd , and the od_sum
  14. int lower_bound, neighbor_bound , od_sum , counts =0;
  15. int arr[count] , lst[count] , in;
  16. // A condition for to loop in O(n^2)
  17. // start at one , add it with the next odd number until it has the od_sum equal to sum and the counts met the given condition
  18. // otherwise we chage the lower bound and add the next one.
  19. for(lower_bound = 1; lower_bound < bound; lower_bound+= 2){
  20. if(count == counts && lower_bound < bound && od_sum ==sum){
  21. break;
  22. }
  23. counts =0;
  24. od_sum = lower_bound;
  25. arr[counts] = lower_bound;
  26. counts ++;
  27. for(neighbor_bound = lower_bound +2 ; (neighbor_bound<bound && counts <= count); neighbor_bound += 2){
  28. od_sum += neighbor_bound;
  29. arr[counts] = neighbor_bound;
  30. counts++;
  31. if(count == counts && neighbor_bound < bound && od_sum == sum){
  32. break;
  33. }
  34. }
  35. }
  36.  
  37.  
  38. if(od_sum == sum){
  39. for (in = 0; in < count; in ++){
  40. lst[in] = arr[in];
  41. printf("%d ", lst[in]);
  42. }
  43. return 1;
  44. }
  45.  
  46. return 0;
  47. }
  48.  
  49. /* Do not change the main() function */
  50. int main(void)
  51. {
  52. int value;
  53. int c, b, s;
  54.  
  55. printf("Please enter 3 positive integers: count, bound, and sum:\n");
  56. if (scanf("%d%d%d", &c, &b, &s) != 3) {
  57. printf("Please enter 3 integers.\n");
  58. return 1;
  59. }
  60.  
  61. if (c <= 0 || b <= 0 || s <= 0) {
  62. printf("Integers must be positive.\n");
  63. return 1;
  64. }
  65.  
  66. value = odd_sum(c, b, s);
  67. if (value)
  68. printf("\n");
  69. else
  70. printf("There are no solutions.\n");
  71. return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement