Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- /* Search for `count' distinct odd numbers that
- * are smaller than `bound' and add up to `sum'.
- *
- * Return value:
- * 1: A solution is found and printed.
- * 0: No solution was found.
- */
- int odd_sum(int count, int bound, int sum)
- {
- // Initialize the lower bound , the next odd , and the od_sum
- int lower_bound, neighbor_bound , od_sum , counts =0;
- int arr[count] , lst[count] , in;
- // A condition for to loop in O(n^2)
- // 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
- // otherwise we chage the lower bound and add the next one.
- for(lower_bound = 1; lower_bound < bound; lower_bound+= 2){
- if(count == counts && lower_bound < bound && od_sum ==sum){
- break;
- }
- counts =0;
- od_sum = lower_bound;
- arr[counts] = lower_bound;
- counts ++;
- for(neighbor_bound = lower_bound +2 ; (neighbor_bound<bound && counts <= count); neighbor_bound += 2){
- od_sum += neighbor_bound;
- arr[counts] = neighbor_bound;
- counts++;
- if(count == counts && neighbor_bound < bound && od_sum == sum){
- break;
- }
- }
- }
- if(od_sum == sum){
- for (in = 0; in < count; in ++){
- lst[in] = arr[in];
- printf("%d ", lst[in]);
- }
- return 1;
- }
- return 0;
- }
- /* Do not change the main() function */
- int main(void)
- {
- int value;
- int c, b, s;
- printf("Please enter 3 positive integers: count, bound, and sum:\n");
- if (scanf("%d%d%d", &c, &b, &s) != 3) {
- printf("Please enter 3 integers.\n");
- return 1;
- }
- if (c <= 0 || b <= 0 || s <= 0) {
- printf("Integers must be positive.\n");
- return 1;
- }
- value = odd_sum(c, b, s);
- if (value)
- printf("\n");
- else
- printf("There are no solutions.\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement