循环-23. 找完数(20)

所谓完数就是该数恰好等于除自身外的因子之和。例如: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;  
}  

  

原文地址:https://www.cnblogs.com/ligen/p/4262036.html