Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2501259
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2011-04-26 18:08:11

    已知一个正整数n,编写一个程序,找出所有满足x*x + y*y = n的正整数对x和y.
    我们知道n的平方根乘以n的平方根等于n,所以x,y的最大值为n的平方根,所以我们通过穷举法,就可求出x,y的值,编写代码如下:
  1. #include <stdio.h>
  2. #include <math.h>

  3. void getXY(int n)
  4. {
  5.   int x,y;
  6.   for(x=1; x<sqrt(n); x++)
  7.     for(y=x; y<sqrt(n); y++)
  8.       if(x*x+y*y == n)
  9.         printf("%d*%d + %d*%d = %d\n",x,x,y,y,n);
  10. }


  11. int main(int argc, char *argv[])
  12. {
  13.   int n;
  14.   printf("please input a integer\n");
  15.   scanf("%d",&n);
  16.   getXY(n);

  17.   return 0;
  18. }
程序执行结果如下:
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ gcc 6.2.c -lm
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out 
please input a integer
100
6*6 + 8*8 = 100
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out 
please input a integer
200
2*2 + 14*14 = 200
10*10 + 10*10 = 200

阅读(2569) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~