版权声明:转载请声明原文链接地址,谢谢! https://blog.csdn.net/weixin_42859280/article/details/84930990
写在前面,心得感悟~
代码越来越有难度!
这个ACM题,我调试了
将近50次~
一个小时!
真的是,年纪轻轻的搞什么ACM呀!
关于题的解决思路放在下面再写吧!
题目描述
一个数如果恰好等于它的因子之和,这个数就称为"完数"。
例如,6的因子为1、2、3,而6=1+2+3,因此6是"完数"。
编程序找出N之内的所有完数,并按下面格式输出其因子:
输入
N
输出
? its factors are ? ? ?
样例输入
1000
样例输出
6 its factors are 1 2 3
28 its factors are 1 2 4 7 14
496 its factors are 1 2 4 8 16 31 62 124 248
来源/分类
C语言
题目照片:
解题思路:
数量很多,先想到就是用两层for循环啦!
for(j=1;j<=a;j++)
{
for(int i=1;i<=j;i++)
{
}
}
是找出因子的,就要用到%运算。
if(j%i==0)
这样就会从1到你输入的数都会计算出它的因子啦!
那么接下来就是存储这些个因子啦!首先想到就是用数组!
但是,是每一次都要存储因子。满足条件再进行输出!
所以要把它放在第二个for循环前面。每次都要初始化为空数组!
int s=0; c=0;m=0;int t[100]={0};
一些其他的,
s是用来进行判断的!要初始化!
c是用来决定输出与否的!
m是数组的下角标数值!
把所有因子,包括1,但是不包括自己。相加!
就是上面这句话实现起来真的是有点难度呀!失败了好多次,才想到用两个if函数来进行修改!
来跟s对比值的大小,来修改C的值,通过c来决定是否输出数组!
代码:(注释较多,就是为了能够清楚看到代码执行过程!)
#include<iostream>
using namespace std;
int main()
{
int a,b,c,i,j,m;int s[100]={0};
cin>>a;
for(j=1;j<=a;j++)
{int s=0; c=0;m=0;int t[100]={0};
//cout<<j<<" j开始循环! "<<endl;
for(int i=1;i<=j;i++)
{
// cout<<"j "<<j;
// cout<<" i "<<i;
if(j%i==0)
if(i==1)
{ s+=i;
// cout<<endl;cout<<endl;
// cout<<" m "<<m;
// cout<<" i "<<i;
// cout<<" s "<<s;
// cout<<endl;cout<<endl;
t[m]=i;
m++;
if(j==s)
{
// cout<<"这个时候j==s!"<<endl;
c=100;
// cout<<"这个时候c==1!"<<endl;
// s-=1000;
}
}
else
{
if(j!=1&&i!=1&&j!=i)
{
{ s+=i;
// cout<<endl;cout<<endl;
// cout<<" m "<<m;
// cout<<" i "<<i;
// cout<<" s "<<s;
// cout<<endl;cout<<endl;
t[m]=i;
m++;
}
}
}
}
//cout<<" s "<<s<<endl;
//cout<<" j "<<j<<endl;
if(j==s)
{
// cout<<"这个时候j==s!"<<endl;
c=100;
// cout<<"这个时候c==1!"<<endl;
// s-=1000;
}
//cout<<"这个时候c! "<<c<<endl;
if(c>50&&j!=1)
{
cout<<j<<" its factors are";
for(int i=0;i<m;i++)
{
cout<<" "<<t[i];
}cout<<endl;
}
}
}
代码截图:
代码执行结果:
OJ结果: