Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Aliquot Sequence (ลำดับอาลิโควท) ใน C++


บทนำ

Aliquot Sequence: เริ่มจากตัวเลข n ตัวถัดไป = ผลรวมตัวหารที่แท้จริง (proper divisors) ของตัวก่อนหน้า (ไม่รวมตัวมันเอง)

ตัวอย่าง

n=8: ตัวหารของ 8 คือ 1,2,4 → sum=7 → ตัวหารของ 7 คือ 1 → sum=1 → ตัวหารของ 1 คือ ไม่มี → sum=0 → Sequence: 8, 7, 1, 0

จำนวนพิเศษ

  • Perfect Number: Aliquot sequence ยาว 1 (เช่น 6 → 6)
  • Amicable Number: ยาว 2 (เช่น 220 ↔ 284)
  • Sociable Number: ยาว 3 หรือมากกว่า

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

int Sumfactorial(int n) {
    int sum = 0;
    for (int i = 1; i <= sqrt(n); i++) {
        if (n % i == 0) {
            if (n / i == i) sum += i;
            else { sum += i; sum += n / i; }
        }
    }
    return sum - n;  // proper divisors only
}

void Aliquotsequence(int n) {
    printf("%d ", n);
    unordered_set s;
    s.insert(n);
    while (n > 0) {
        n = Sumfactorial(n);
        if (s.find(n) != s.end()) {
            cout << "\nRepeats with " << n;
            break;
        }
        cout << n << " ";
        s.insert(n);
    }
}

int main() {
    Aliquotsequence(45);
    return 0;
}

ผลลัพธ์

45 33 15 9 4 3 1 0