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

โปรแกรม C ตรวจสอบ Betrothed Numbers

Betrothed Numbers คือคู่เลข (a,b) ที่ผลรวมตัวหารของ a (ไม่รวม a) = b+1 และของ b = a+1

ตัวอย่างคู่แรกๆ

(48, 75), (140, 195), (1050, 1925), (1575, 1648)

ตรวจสอบ 48 และ 75

  • ตัวหารของ 48: 1,2,3,4,6,8,12,16,24 → ผลรวม = 76 = 75+1 ✓
  • ตัวหารของ 75: 1,3,5,15,25 → ผลรวม = 49 = 48+1 ✓

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

#include <stdio.h>

int sum_divisors(int n) {
    int sum = 0;
    for (int i = 1; i < n; i++)
        if (n % i == 0) sum += i;
    return sum;
}

int main() {
    int a = 48, b = 75;
    int sa = sum_divisors(a), sb = sum_divisors(b);
    if (sa == b+1 && sb == a+1)
        printf("%d and %d are Betrothed numbers\n", a, b);
    else
        printf("%d and %d are NOT Betrothed numbers\n", a, b);
    return 0;
}

ผลลัพธ์

48 and 75 are Betrothed numbers