数论中四方定理

/*
标题:四方定理


数论中有著名的四方定理:所有自然数至多只要用四个数的平方和就可以表示。
我们可以通过计算机验证其在有限范围的正确性。

对于大数,简单的循环嵌套是不适宜的。下面的代码给出了一种分解方案。

利用递归函数来解决

*/
#include  <iostream.h>
#include  <math.h>
int f(int n, int a[], int idx)
{		int i;
	if(n==0) return 1;  //完成分解过程
	if(idx>3) return 0;
	i=(int)sqrt(n);
	a[idx] = (int)sqrt(n);
	
  f(n-i*i,a,idx+1);	
}

int main(   )
{
	    

		int number;
		
		cout<<"输入整数(1~10亿):";
		while(cin>>number)
		{
			int a[] = {0,0,0,0}; 
			
		int r=	f(number, a, 0); //将分解得到的数依次放到a[0]~a[3]中
		if(r)
			{
				cout<<number<<"分解为以下四个数的平方和"<<endl;
				cout<<" "<<a[0]<<" "<<a[1]<<" "<<a[2]<<" "<<a[3]<<endl;
			}
		else<<"eror"<<endl;
		cout<<"输入整数(1~10亿):";
		}
		return 0;
}
/*
标题:四方定理


数论中有著名的四方定理:所有自然数至多只要用四个数的平方和就可以表示。
我们可以通过计算机验证其在有限范围的正确性。

对于大数,简单的循环嵌套是不适宜的。下面的代码给出了一种分解方案。

利用递归函数来解决

*/
#include  <iostream.h>
#include  <math.h>
int f(int n, int a[], int idx)
{
	if(n==0) return 1;  //完成分解过程
	if(idx==4)  return 0;  //表示已经找出四个数,结束

	for(int i=(int)sqrt(n); i>=1; i--)
	{
		a[idx] = i;

		if( f(n-i*i,a+1,idx)==1)  return 1;  // 填空
	}

	return 0;
}

int main(   )
{
	    

		int number;
		cout<<"输入整数(1~10亿):";
		cin>>number;
	    while(number>0)
		{
		int a[] = {0,0,0,0}; 

		int r = f(number, a, 0); //将分解得到的数依次放到a[0]~a[3]中

        cout<<number<<"分解为以下四个数的平方和"<<endl;
     	cout<<" "<<a[0]<<" "<<a[1]<<" "<<a[2]<<" "<<a[3]<<endl;
		cout<<"输入整数(1~10亿):";
		cin>>number;		
		}
		return 0;
}


点击打开链接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值