HD-6216-A Cubic number and A Cubic Number

来源:互联网 发布:mysql 连接127.0.0.1 编辑:程序博客网 时间:2024/05/30 23:28

Problem Description
A cubic number is the result of using a whole number in a multiplication three times. For example, 3×3×3=27 so 27 is a cubic number. The first few cubic numbers are 1,8,27,64 and 125. Given an prime number p. Check that if p is a difference of two cubic numbers.

Input
The first of input contains an integer T (1≤T≤100) which is the total number of test cases.
For each test case, a line contains a prime number p (2≤p≤1012).

Output
For each test case, output ‘YES’ if given p is a difference of two cubic numbers, or ‘NO’ if not.

Sample Input
10
2
3
5
7
11
13
17
19
23
29

Sample Output
NO
NO
NO
YES
NO
NO
NO
YES
NO
NO

http://mathworld.wolfram.com/CubanPrime.html:只有相邻两个立方数的差可能为质数。

这道题有两种解法,一种是打表,一种是用公式。

打表:

#include <cstdio>const int maxn = 1000000;typedef long long ll;ll i[maxn];int main(){    for(ll a = 2;a < maxn;a ++)//特别注意要long long型的        i[a]=a*a*a-(a-1)*(a-1)*(a-1);    int n;    ll p;    int flag;    scanf("%d",&n);    while(n --)    {        flag = 0;        scanf("%lld",&p);        for(int a = 2;a < maxn;a ++)        {            if(p==i[a])            {                flag=1;                break;            }            if(p<i[a])break;        }        if(flag)            printf("YES\n");        else            printf("NO\n");    }    return 0;}

公式:
x^3-y^3
=(x^3-x^2*y)+x^2*y-(y^3-x*y^2)-x*y^2
=x^2(x-y)-y^2(y-x)+xy(x-y)

=(x-y)(x^2+xy+y^2)=p(p是质数)——> x-y=1以及x^2+xy+y^2=p

代入消元:p=3y^2+3y+1

代码如下

#include <cstdio>typedef long long ll;int main(){    int n;    scanf("%d",&n);    while(n --)    {        ll p;        int flag = 0;        scanf("%lld",&p);        for(ll a = 1;a < 1e6+5;a ++)//特别注意要long long型的        {            if(3*a*a+3*a+1==p)            {                flag = 1;                break;            }            if(3*a*a+3*a+1>p)                break;        }        if(flag)            printf("YES\n");        else            printf("NO\n");    }    return 0;}
原创粉丝点击