HDU 6441 - Find Integer - [費馬大定理][2018CCPC網絡選拔賽第4題]
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=6441
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Problem Description
people in USSS love math very much, and there is a famous math problem .
give you two integers n,a,you are required to find 2 integers b,c such that $a^n + b^n = c^n$.
Input
one line contains one integer T;(1≤T≤1000000)
next T lines contains two integers n,a;(0≤n≤1000,000,000,3≤a≤40000)
Output
print two integers b,c if b,c exits;(1≤b,c≤1000,000,000);
else print two integers -1 -1 instead.
Sample Input
1
2 3
Sample Output
4 5
題意:
給出 $n$ 和 $a$ (0≤n≤1e9,3≤a≤4e4),要求你給出 $b$ 和 $c$ 滿足 $a^n + b^n = c^n$。
題解:
根據費馬大定理,$n > 2$ 時 $a^n + b^n = c^n$ 沒有整數解,所以只需要計算 $n = 0,1,2$ 這三種情況:
1、$n = 0$,任何的正整數 $b,c$ 都無法使等式成立。
2、$n = 1$,任意取。
3、$n = 2$,$a^2 = \left( {c + b} \right)\left( {c - b} \right)$,分兩種情況討論:
若 $a$ 為奇數,則 $a^2$ 也為奇數,則取 $b = \frac{{a^2 - 1}}{2},c = \frac{{a^2 + 1}}{2}$;
若 $a$ 為偶數,則 $a^2$ 必然是 $4$ 的倍數,則取 $b = \frac{{a^2 - 4}}{4},c = \frac{{a^2 + 4}}{4}$。
AC代碼:
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll a,n; int main() { int T; cin>>T; while(T--) { scanf("%lld%d",&n,&a); if(n==0 || n>2) printf("-1 -1\n"); if(n==1) printf("1 %lld\n",a+1); if(n==2) { if(a%2==1) printf("%lld %lld\n",(a*a-1)/2,(a*a+1)/2); else printf("%lld %lld\n",(a*a-4)/4,(a*a+4)/4); } } }
HDU 6441 - Find Integer - [費馬大定理][2018CCPC網絡選拔賽第4題]