สมมติว่าเรามีตัวเลข เราต้องเขียนเป็นผลรวมของจำนวนเต็มสองจำนวน ถ้าใช่ ให้พิมพ์ตัวเลข มิฉะนั้นให้พิมพ์ -1 จำนวนกล่าวว่าเป็นจำนวนมากมายคือผลรวมของตัวหารที่เหมาะสมทั้งหมดของจำนวนซึ่งแสดงโดยผลรวม (n) มากกว่าค่าของตัวเลข
เพื่อแก้ปัญหานี้ เราจะเก็บจำนวนมากมายทั้งหมดไว้ในชุด และสำหรับจำนวนที่กำหนด n ให้รันลูปสำหรับ i =1 ถึง n และตรวจสอบว่า n และ (n – i) มีจำนวนมากเกินไปหรือไม่
ตัวอย่าง
#include <iostream>
#include <set>
#define N 100005
using namespace std;
set<int> getAbundantSet() {
set<int> abundant_set;
for (int i = 1; i < N; i++) {
int sum = 1;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
sum += j;
if (i / j != j)
sum += i / j;
}
}
if (sum > i)
abundant_set.insert(i);
}
return abundant_set;
}
void representSumAbundant(int number){
set<int> abundant_set = getAbundantSet();
for (int i = 1; i <= number; i++) {
if (abundant_set.count(i) && abundant_set.count(number - i)) {
cout << i << " " << number - i;
return;
}
}
cout << -1;
}
int main() {
int n = 30;
representSumAbundant(n);
} ผลลัพธ์
12 18