亲和数(C++的简单题目)

问题描述
古希腊数学家毕达哥拉斯在自然数研究中发现,220的所有真约数(即不是自身的约数)之和为:

1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110=284。

而284的所有真约数为1、2、4、71、 142,加起来恰好为220。人们对这样的数感到很惊奇,并称之为亲和数。
 一般地讲,如果两个数中任何一个数都是另一个数的真约数之和,则这两个数就是亲和数。
你的任务就编写一个程序,判断给定的两个数是否是亲和数

输入
输入数据第一行包含一个数M,接下有M行,每行一个实例, 包含两个整数A, B; 其中 0 <=A, B <=600000;

输出
对于每个测试实例,如果A和B是亲和数的话输出YES,否则输出NO。

样例输入
2
220 284
100 200
样例输出
YES
NO

代码如下:

#include<iostream>
using namespace std;
int main() {
	int M;
	cin >> M;
	for (int i = 0; i < M; i++) {
		int a, b;
		cin >> a >> b;
		if (a < 0 || a>600000 || b < 0 || b>600000) {
			return 0;
		}
		int suma = 0;
		for (int i = 1; i < a; i++) {
			if (a % i == 0) {
				suma += i;
			}
		}
		int sumb = 0;
		for (int i = 1; i < b; i++) {
			if (b % i == 0) {
				sumb += i;
			}
		}
		if (suma == b && sumb == a) {
			cout << "YES" << endl;
		}
		else {
			cout << "NO" << endl;
		}
	}
	return 0;
}

### 关于东方博宜 OJ 平台1862号问题(友好)的C++解决方案 对于编写能够成功提交并通过测试案例的程序而言,理解题目要求至关重要。通常,“友好”的定义涉及到两个整之间的某种特定关系,在此假设“友好”是指欧拉计划中的亲和概念。 下面是一个简单C++ 实现来查找并打印一对给定范围内的最小亲和: ```cpp #include <iostream> using namespace std; int sumOfDivisors(int n){ int sum = 1; // Start with 1 because it is always a proper divisor. for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { sum += i; if ((n / i) != i) { // Avoid adding square root twice when perfect squares are encountered sum += n / i; } } } return sum; } pair<int, int> findAmicablePair(int limit) { pair<int, int> result(0, 0); bool found = false; for (int numA = 2; !found && numA <= limit; ++numA) { int numB = sumOfDivisors(numA); if (numB > numA && sumOfDivisors(numB) == numA) { result.first = numA; result.second = numB; found = true; } } return result; } int main() { const int LIMIT = 10000; // Define the upper bound of your search here. auto amicableNumbers = findAmicablePair(LIMIT); cout << "Smallest Amicable Pair within given range: (" << amicableNumbers.first << ", " << amicableNumbers.second << ")" << endl; return 0; } ``` 编译上述代码时建议使用 `g++` 而不是 `gcc`, 这样可以避免手动指定 `-lstdc++` 参[^1]。此外,《C++ Primer》作为权威性的参考资料可以帮助深入理解和掌握更多关于 C++ 编程的知识[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值