Home > Software engineering >  Combinations Two Numbers (x and y)
Combinations Two Numbers (x and y)

Time:11-30

I wanted to solve a problem that is a combination of x and y (in this case 11 and 15) and check if the number (c) is a combination of those numbers with YES or NO 11x 15y = c

#include <stdio.h>

int separate_as(int c, int a, int b, int *x, int *y)
{
    *x = 0;
    for (; c % b != 0 && (c > a); c -= a, (*x)  );
    if (c < a && c < b) return -1;
    
    *y = c / b;
    
    return 0;
}

int main()
{
    int times;
    int c;
    int x,y;

    scanf("%d", &times);
    for (int i=0; i<times; i  )
    {
        scanf("%d", &c);
        

    }
    for (int z=0; z<times; z  ) 
        {
            
            if (separate_as(c, 15, 11, &x, &y) == -1)
            {
            printf("NO\n");
            
        }
        
            else if (separate_as(c, 15, 11, &x, &y) == 0)
            {
            printf("YES\n");
            
        }
        else
        {
        printf("NO\n");
        }
        }   
        
    
    return 0;
}

Input:

5 (the number of n input)
89
234
876
99
12

Output:

YES
YES
YES
YES
YES

Expected output:

YES
YES
YES
YES
NO

CodePudding user response:

Fun little problem.
But it looks like you made it awfully complex in your code.
Here's an easy solution.

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    const int factor1 = 11;
    const int factor2 = 15;
    
    const int input[] = {89, 234, 876, 99, 12};
    const int n = 5;
    
    for(int i=0; i<n;   i)
    {
        bool solution = false;
        for(int x=0; x <= input[i]/factor1;   x)
        {
            int y = (input[i]-factor1*x)/factor2;
            if (factor1*x   factor2*y == input[i])
            {
                printf("%d = %d*%d   %d*%d\n", input[i], factor1, x, factor2, y);
                solution = true;
                break;
            }
        }
        printf("Input %d: Solution %s\n\n", input[i], solution? "YES" : "NO");
    }
    
    return 0;
}

Output

Success #stdin #stdout 0s 5380KB
89 = 11*4   15*3
Input 89: Solution YES

234 = 11*9   15*9
Input 234: Solution YES

876 = 11*6   15*54
Input 876: Solution YES

99 = 11*9   15*0
Input 99: Solution YES

Input 12: Solution NO
  •  Tags:  
  • c
  • Related