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

เลขลัคกี้ (Lucky Numbers)

บทนำ

เลขลัคกี้ (Lucky Numbers) คือจำนวนเต็มพิเศษบางจำนวน จากชุดตัวเลขพื้นฐาน จะมีการกำจัดตัวเลขพิเศษบางตัวตามตำแหน่งของมัน ไม่ใช่ตามค่า ตัวเลขที่ไม่ถูกกำจัด คือเลขลัคกี้

การกำจัดตัวเลขมีกฎดังนี้: ก่อนอื่นกำจัดทุกตัวที่ 2 จากนั้นกำจัดทุกตัวที่ 3 และต่อไปเรื่อยๆ

ตัวอย่าง

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 (1-25 ทั้งหมด)
1 3 5 7 9 11 13 15 17 19 21 23 25 (กำจัดทุกตัวที่ 2)
1 3 7 9 13 15 19 21 25 (กำจัดทุกตัวที่ 3 เริ่มจาก 5)
1 3 7 9 13 15 21 25 (กำจัดทุกตัวที่ 7 เริ่มจาก 19)

อินพุตและเอาต์พุต

Input: ใส่ตัวเลขเพื่อตรวจสอบว่าเป็นเลขลัคกี้หรือไม่ สมมติตัวเลขคือ 13

Output: 13 เป็นเลขลัคกี้

อัลกอริทึม

isLuckyNumber(number)
Input: ตัวเลขหนึ่งตัว
Output: ตรวจสอบว่าตัวเลขเป็นลัคกี้หรือไม่

Begin
    counter := 2 (เป็นข้อมูล static ไม่ได้ initialize ใหม่ในการเรียกซ้ำ)
    if counter > n, then
        return 1
    if n mod counter = 0, then
        return 0
    n := n - (n / counter)
    counter := counter + 1
    isLuckyNumber(n)
End

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

#include <iostream>
using namespace std;

int counter = 2;  // ใช้ในการเรียกซ้ำ
bool isLuckyNumber(int n) {
    if (counter > n)
        return 1;
    if (n % counter == 0)
        return 0;
    n -= n / counter;  // n จะเป็นตำแหน่งถัดไปสำหรับ recursion
    counter++;
    return isLuckyNumber(n);
}

int main() {
    int x = 13;
    if (isLuckyNumber(x))
        cout << x << " is a lucky number.";
    else
        cout << x << " is not a lucky number.";
}

ผลลัพธ์

13 is a lucky number.