Ramanujan-Nagell方程求解程序

来源:互联网 发布:linux系统硬盘克隆 编辑:程序博客网 时间:2024/06/10 02:43

Ramanujan-Nagell方程求解程序

 M. B. Nathanson所著《Elementary Methods in Number Theory》第42页给出了下面一个问题:当x<=1000时,寻求方程x^2+7=2^n的全部解。
当x<=1000时,x^2+7=2^n<=1000007,这时n<=19。因此,在设计算法时,可以对每个n,生成2^n-7,并判断是否平方数,这样可以节省计算时间。
在实际的程序中,我们判断n在[3,30]之内的所有可能的解。
n   2^n     n       2^n
1   2        17     131072
2   4       18      262144
3   8       19      524288
4   16     20     1048576
5   32     21     2097152
6   64     22     4194304
7   128   23     8388608
8   256   24     16777216
9   512   25     33554432
10 1024 26     67108864
11 2048 27    134217728
12 4096 28    268435456
13 8192 29    536870912
14 16384 30 1073741824
15 32768 31 2147483648
16 65536 32 4294967296
程序如下:
// File: eq_ramnag.c

#include <stdio.h>
#include <math.h>

#define BOOL int
#define TRUE 1
#define FALSE 0

BOOL isSqr(int v, int *x);

void main()
{
 int n, x;
 int p2, v;

 p2 = 4;
 for (n = 3; n <= 30; n++)
 {
  p2 = p2 * 2;
  v = p2 - 7;
  if (isSqr(v, &x))
   printf("%d^2+7=2^%d/n", x, n);
 }
}

BOOL isSqr(int v, int *x)
{
 int y;

 y = (int)sqrt((double)v);
 if (y*y == v)
 {
  *x = y;
  return TRUE;
 }

 return FALSE;
}

程序运行得到下列解:
1^2+7=2^3
3^2+7=2^4
5^2+7=2^5
11^2+7=2^7
181^2+7=2^15

 

原创粉丝点击