C语言 两个数字的组合(x和y)

ddrv8njm  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(859)

我想解决一个x和y的组合问题(在本例中为11和15),并检查数字(c)是否为这些数字的组合,是否为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;
}

输入:

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

输出:

YES
YES
YES
YES
YES

预期输出:

YES
YES
YES
YES
NO
qgzx9mmu

qgzx9mmu1#

有趣的小问题。
但看起来你在代码中把它弄得非常复杂。
这里有一个简单的解决方案。

#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;
}

输出

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

相关问题