当前位置: 代码迷 >> 综合 >> PAT_B_循环-23. 找完数(20)
  详细解决方案

PAT_B_循环-23. 找完数(20)

热度:87   发布时间:2024-01-19 05:12:23.0

循环-23. 找完数(20)

时间限制
100 ms
内存限制
32000 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈建海(浙江大学)
来源
ZOJ

所谓完数就是该数恰好等于除自身外的因子之和。例如:6=1+2+3,其中1、2、3为6的因子。本题要求编写程序,找出任意两正整数m和n之间的所有完数。

输入格式:

输入在一行中给出2个正整数m和n(0<m<=n<=10000),中间以空格分隔。

输出格式:

逐行输出给定范围内每个完数的因子累加形式的分解式,每个完数占一行,格式为“完数 = 因子1 + 因子2 + ... + 因子k”,其中完数和因子均按递增顺序给出。

输入样例:

1 30

输出样例:

1 = 1
6 = 1 + 2 + 3

28 = 1 + 2 + 4 + 7 + 14

#include <iostream>
#include <math.h>using namespace::std;bool isWanshu(int  n)
{int i;string str="1";string str2="";int sum=1;for (i=2; i<=sqrt(n); i++) {if (n%i==0) {int m=n/i;char buf[10];sprintf(buf, " + %d", i);string b = buf;str+=b;if (m!=n) {sum+=(i+n/i);sprintf(buf, " + %d", n/i);b = buf;str2=b+str2;}else{sum+=i;}}}if (sum==n) {cout<<n<<" = "<<str<<str2<<endl;return true;}else{return false;}
}int main(int argc, const char * argv[])
{int i=1;int n,m ;cin>>m>>n;for (i=m ; i<=n; i++) {isWanshu(i);}return 0;
}


  相关解决方案