Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Kiểm tra số Armstrong trong C

Số Armstrong (Số narcissistic) là gì?

Số Armstrong là số bằng tổng các chữ số của nó lũy thừa theo số chữ số.

Ví dụ với 3 chữ số: abc = a³ + b³ + c³

  • 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓
  • 371 = 3³ + 7³ + 1³ = 27 + 343 + 1 = 371 ✓
  • 1634 = 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1 + 1296 + 81 + 256 = 1634 ✓ (4 chữ số)

Thuật toán

  1. Lưu số gốc vào biến tạm
  2. Dùng vòng lặp while tách từng chữ số (mod 10, chia 10)
  3. Tính lũy thừa và cộng dồn
  4. So sánh kết quả với số gốc

Chương trình C (dành cho số 3 chữ số)

#include <stdio.h>

int main() {
    int so, tam, du, tong = 0;
    
    printf("Nhap so can kiem tra: ");
    scanf("%d", &so);
    
    tam = so;  // Lưu số gốc
    
    while (so > 0) {
        du = so % 10;           // Lấy chữ số cuối
        tong += du * du * du;   // Lũy thừa 3 (vì 3 chữ số)
        so /= 10;               // Bỏ chữ số cuối
    }
    
    if (tam == tong)
        printf("%d la so Armstrong\n", tam);
    else
        printf("%d KHONG la so Armstrong\n", tam);
    
    return 0;
}

Kết quả chạy chương trình

Nhap so can kiem tra: 371
371 la so Armstrong
Kiem tra: 371 = 3*3*3 + 7*7*7 + 1*1*1 = 27 + 343 + 1 = 371

Nhap so can kiem tra: 53
53 KHONG la so Armstrong
Kiem tra: 53 = 5*5*5 + 3*3*3 = 125 + 27 = 152 != 53

Chương trình mở rộng: Kiểm tra số Armstrong bất kỳ số chữ số

#include <stdio.h>
#include <math.h>

int demChuSo(int n) {
    int dem = 0;
    if (n == 0) return 1;
    while (n > 0) {
        dem++;
        n /= 10;
    }
    return dem;
}

int main() {
    int so, tam, du, tong = 0, soChuSo;
    
    printf("Nhap so: ");
    scanf("%d", &so);
    
    tam = so;
    soChuSo = demChuSo(so);
    
    while (so > 0) {
        du = so % 10;
        tong += pow(du, soChuSo);  // Lũy thừa theo số chữ số
        so /= 10;
    }
    
    if (tam == tong)
        printf("%d la so Armstrong (%d chu so)\n", tam, soChuSo);
    else
        printf("%d KHONG la so Armstrong\n", tam);
    
    return 0;
}

Các số Armstrong nhỏ

1 chữ số: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
3 chữ số: 153, 370, 371, 407
4 chữ số: 1634, 8208, 9474
5 chữ số: 54748, 92727, 93084

Lưu ý: Cần include <math.h> và compile với flag -lm (gcc) để dùng pow().