完数查找

如果一个正整数的所有真因子(不含本身)之和等于自身,该正整数称为完数。本题要求利用STL容器保存输入的若干个正整数,并利用函数对象和STL算法统计其中完数个数,如果有完数,输出第1个完数的序号和第一个完数,如果没有,输出none

#include 
   
   
    
    
#include 
    
    
     
     
#include 
     
     
      
      
using namespace std;

class Perfect_Number
{
public:
    bool operator() (int v)
    {
        int sum = 0;//用来存储当前正整数的真因子
        for (int i = 1; i < v; i++) {
            if ((v % i) == 0)//若为其真因子
                sum += i;
        }
        if (sum == v)
            return true;
        else
            return false;
    }
};
int main()
{
    vector
      
      
       
        v;
    int x;
    while (cin >> x)
        v.push_back(x);
    int count = count_if(v.begin(), v.end(), Perfect_Number());//STL算法
    cout << count << endl;
    if(count==0)
        cout << "none" <
       
       
         ::iterator first = find_if(v.begin(), v.end(), Perfect_Number()); cout << first-v.begin()+1 << " " << *first << endl; } return 0; } 
       
      
      
     
     
    
    
   
   

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值