c语言勾股数程序题scau,UVa:106 Fermat vs. Pythagoras

这个题如果不看题解,是肯定没办法AC的。

大致说一下方法。

a=s*t

b=(s*s-t*t)/2

c=(s*s+t*t)/2

a*a+b*b==c*c

其中,s>t>=1且互质并皆为奇数。据此可以枚举s,t,另外注意利用a,b

这是素勾股数的构造办法,其余勾股数可以通过倍增来找到。

#include

#include

#include

#include

#include

#include

#include

#define MAXN 1000005

#define MOD 1000000007

#define INF 2139062143

#define ll long long

using namespace std;

ll gcd(ll a,ll b)

{

return !a?b:gcd(b%a,a);

}

bool vis[MAXN];

int main()

{

int N;

while(scanf("%d",&N)!=EOF)

{

memset(vis,0,sizeof(vis));

int m=sqrt(N*1.0);

int cnt1=0,cnt2=0;

for(ll t=1; t<=m; t+=2)

for(ll s=t+2; s*t<=N; s+=2)

{

if(gcd(s,t)==1)

{

ll a=s*t,b=(s*s-t*t)/2,c=(s*s+t*t)/2;

if(c<=N)

{

cnt1++;

vis[a]=vis[b]=vis[c]=true;

for(int l=2;l*c<=N;++l)

vis[l*a]=vis[l*b]=vis[l*c]=true;

}

}

}

for(int i=1;i<=N;++i)

if(!vis[i]) cnt2++;

printf("%d %d\n",cnt1,cnt2);

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值