欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

满数和盈数

程序员文章站 2022-03-15 19:30:01
...
一个数如果恰好等于它的各因子(该数本身除外)子和,
如: 6=3+2+1,则称其为“完数”;若因子之和大于该数,则称其为“盈数”。
求出 260 之间所有“完数”和“盈数”,
并以如下形式输出:
 E: e1 e2 e3 ......(ei 为完数)
 G: g1 g2 g3 ......(gi 为盈数)

1.模拟题,核心是分解因子。直接打表,先找到表然后输出。

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;


class Solution
{
private:
	int begin, end;
	vector<int> E, G;
public:
	Solution() {}
	Solution(int from, int to) :begin(from), end(to) {}
	~Solution() {}

	void getEandG() {
		for (int number = begin; number <= end; ++number)
		{
			int sumOfDivisors = findSumOfNumberDivisors(number);
			pushBackToRightVector(sumOfDivisors, number);
		}
	}

	int findSumOfNumberDivisors(const int &number) {
		int sum = 0, smallDivisor = 2;
		while (smallDivisor <= (int)sqrt(number))
		{
			if (number % smallDivisor == 0)
			{
				sum += smallDivisor;
				int bigDivisor = number / smallDivisor;
				if (bigDivisor > smallDivisor)
					sum += bigDivisor;
			}
			smallDivisor++;
		}
		return sum + 1;
	}
	void pushBackToRightVector(const int &sumOfDivisors, const int &number) {
		if (sumOfDivisors > number)
		{
			G.push_back(number);
		}
		else if (sumOfDivisors == number)
		{
			E.push_back(number);
		}
		else
		{
			;
		}
	}

	void showInfoOfEandG() {
		printf("E: ");
		for (int e_number : E) {
			cout << e_number << " ";
		}
		cout << endl;

		printf("G: ");
		for (int g_number : G) {
			cout << g_number << " ";
		}
		cout << endl;
	}
};


int main()
{
	Solution test(2, 60);
	test.getEandG();
	test.showInfoOfEandG();
	system("pause");
	return 0;
}

相关标签: 算法的乐趣