HDU 2092 整数解 (暴力/解方程)

Description

有二个整数,它们加起来等于某个整数,乘起来又等于另一个整数,它们到底是真还是假,也就是这种整数到底存不存在,实在有点吃不准,你能快速回答吗?看来只能通过编程。

例如:

x + y = 9,x * y = 15 ? 找不到这样的整数x和y

1+4=5,1*4=4,所以,加起来等于5,乘起来等于4的二个整数为1和4

7+(-8)=-1,7*(-8)=-56,所以,加起来等于-1,乘起来等于-56的二个整数为7和-8

Input

输入数据为成对出现的整数n,m(-10000<n,m<10000),它们分别表示整数的和与积,如果两者都为0,则输入结束。

Output

只需要对于每个n和m,输出“Yes”或者“No”,明确有还是没有这种整数就行了。

Sample Input

9 15
5 4
1 -56
0 0

Sample Output

No
Yes
Yes
题目数据量小可以暴力求解,也可以解方程
暴力…就是从9999到-9999枚举x,y=n-a,判断xy等不等于m
解方程
联立得x
x - n*x + m = 0
用万能公式判断两解是否存在且为整数

代码

解方程
#include<bits/stdc++.h>
#include<iostream>
#include<string.h>
#include<vector>
#include<time.h>
#include<stdio.h>
#define ll long long
using namespace std;
int main()
{
    int n,m;
    while(~scanf("%d %d",&n,&m)&&(n||m))
    {
        int ans=0;
        double d=(double)(n*n-4*m);
        if(d==0)
        {
            if(n%2==0)//b%(a*2)==0
                ans=1;
        }
        else if(d>0)
        {
            double x=(n+sqrt(d))/2;
            double y=(n-sqrt(d))/2;
            if(x-(int)x==0||y-(int)y==0)
            ans=1;
        }
        if(ans)
            printf("Yes\n");
        else
            printf("No\n");
    }
}

暴力
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
#include<math.h>
#include<stdio.h>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int main()
{
    int n,m;
    while(~scanf("%d %d",&n,&m))
    {
        if(n==0&&m==0)
        break;
        int ans=0;
        int a=9999;
        int b=n-a;
        while(a>-10000&&b<10000)
        {
            if(a*b==m)
            {
                ans=1;
                break;
            }
            --a;
            ++b;
        }
        if(ans)
            printf("Yes\n");
        else
            printf("No\n");
    }
}

发布了145 篇原创文章 · 获赞 30 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43984169/article/details/96314733