• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

# 求一个数的约数和

5小时前 3次浏览

给你一个数，让你求这个数的所有约数和，6的约数为1，2，3，6。1+2+3+6=12。输出12

c++代码实现从小到大输出这些约数，并且计算约数和

``````#include <iostream>
#include <algorithm>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::sort;
using std::vector;

int main(){
int N，sum=0;
cin >> N;
vector<int> ords;
for (int i = 1; i * i <= N; i++) {
if (N % i == 0) {
ords.push_back(i);
if (i * i != N)
ords.push_back(N / i);
}
}
sort(ords.begin(), ords.end());
cout << ords.size();
for (int i = 0; i < ords.size(); i++){
cout << ' ' << ords[i];
sum+=ords[i];
}
cout<<"约数和sum = "<< sum << endl;
return 0;
}
``````

``````#include <iostream>
#include <algorithm>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::sort;
using std::vector;

vector<int> CalculationDivisor(int N) {
vector<int> ords;
for (int i = 1; i * i <= N; i++) {
if (N % i == 0) {
ords.push_back(i);
if (i * i != N)
ords.push_back(N / i);
}
}
sort(ords.begin(), ords.end());
return ords;
}

void OutputEveryDivisor(vector<int> ords) {
cout << "约数个数为: " << ords.size() << endl;
for (int i = 0; i < ords.size(); i++) {
cout << ' ' << ords[i];
}
cout << endl;
}

int CalculationSumOfDivisor(vector<int> ords) {
int sum = 0;
for (int i = 0; i < ords.size(); i++) {
sum += ords[i];
}
return sum;
}

int main(){
int N，sum=0;
cin >> N;
vector<int> ords;
ords = CalculationDivisor(N);
OutputEveryDivisor(ords);
sum = CalculationSumOfDivisor(ords);
cout<<"约数和：sum = "<< sum << endl;
return 0;
}
``````

6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248