C 语言中的亲和数?
这里我们将看到亲和数,这是一组数字,其中一个数字的真因数求和比另一个数字多 1。我们必须找到这些组
例如,一对数字像 (48, 75)。那么 48 的因数是 {1, 2, 3, 4, 6, 8, 12, 16, 24},求和为 76。类似的,75 的因数是 {1, 3, 5, 15, 25},求和为 49。
算法
BetrothedPairs (n) −
begin for num in range 1 to n, do sum := 1 for i in range 2 to num, do if num is divisible by i, then sum := sum + i if i * i is not same as num, then sum := sum + num / i end if end if if sum > num, then num2 := sum – 1 sum2 := 1 for j in range 2 to num2, do if num2 is divisible by j, then sum2 := sum2 + j if j * j is not same as num2, then sum2 := sum2 + num2 / j end if end if done if sum2 = num + 1, then print the pair num and num2 end if end if done done end
示例
#include <iostream>
using namespace std;
void BetrothedPairs(int n) {
for (int num = 1; num < n; num++) {
int sum = 1;
for (int i = 2; i * i <= num; i++) { //go through each number to get proper divisor
if (num % i == 0) {
sum += i;
if (i * i != num) //avoid to include same divisor twice
sum += num / i;
}
}
if (sum > num) {
int num2 = sum - 1;
int sum2 = 1;
for (int j = 2; j * j <= num2; j++){
if (num2 % j == 0) {
sum2 += j;
if (j * j != num2)
sum2 += num2 / j;
}
}
if (sum2 == num+1)
cout << "(" << num << ", " << num2 <<")" << endl;
}
}
}
int main() {
int n = 5000;
BetrothedPairs(n);
}输出
1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP