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

ตรวจสอบว่าเลขเป็น Full Prime หรือไม่ ใน C++


Full Prime = จำนวนเฉพาะ และทุกหลักเลขก็เป็นจำนวนเฉพาะด้วย

ตัวอย่าง: 37 = Full Prime, 97 ไม่ใช่ (9 ไม่ใช่จำนวนเฉพาะ)

วิธี: ตรวจสอบทุกหลักเลขต้องเป็น 2,3,5,7 เท่านั้น แล้วค่อยตรวจสอบตัวเลขทั้งหมดว่าเป็นเฉพาะหรือไม่

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

#include <iostream>
using namespace std;

bool isPrime(int n) {
    for(int i = 2; i <= n/2; i++)
        if(n % i == 0) return false;
    return true;
}

bool isDigitPrime(int n) {
    int temp = n, digit;
    while(temp) {
        digit = temp % 10;
        if(digit != 2 && digit != 3 && digit != 5 && digit != 7) return false;
        temp = temp / 10;
    }
    return true;
}

bool isFullPrime(int n) { return (isDigitPrime(n) && isPrime(n)); }

int main() {
    int num = 37;
    if (isFullPrime(num)) cout << "The number is Full Prime";
    else cout << "The number is not Full Prime";
}

ผลลัพธ์

The number is Full Prime