ภาพรวมปัญหา
ได้รับตัวเลข N ต้องพิมพ์ "Prime Points" ทั้งหมด (ดัชนีที่แบ่งตัวเลขเป็นสองจำนวนเฉพาะ: ด้านซ้ายและด้านขวา) ถ้าไม่มีให้พิมพ์ -1
ตัวอย่าง
Input: 2359 Output: 1 Explanation: แบ่งที่ดัชนี 1 ได้ 2 และ 59 ทั้งคู่เป็นจำนวนเฉพาะ
วิธีแก้ปัญหา
- นับจำนวนหลักของตัวเลข
- ลองแบ่งที่ทุกตำแหน่งที่เป็นไปได้ (ยกเว้นขอบ)
- แยกส่วนซ้ายและขวา แล้วตรวจสอบจำนวนเฉพาะ
- ถ้าทั้งคู่เป็นจำนวนเฉพาะ → พิมพ์ดัชนี
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
int countDigits(int n) {
int count = 0;
while (n > 0) { count++; n = n/10; }
return count;
}
int checkPrime(int n) {
if (n <= 1) return -1;
if (n <= 3) return 0;
if (n % 2 == 0 || n % 3 == 0) return -1;
for (int i = 5; i*i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0) return -1;
return 0;
}
void primePoints(int n) {
int count = countDigits(n);
if (count == 1 || count == 2) { cout << "-1"; return; }
bool found = false;
for (int i = 1; i < (count - 1); i++) {
int left = n / ((int)pow(10, count - i));
int right = n % ((int)pow(10, count - i - 1));
if (checkPrime(left) == 0 && checkPrime(right) == 0) {
cout << i << "\t";
found = true;
}
}
if (!found) cout << "-1";
}
int main() {
int N = 2359;
cout << "All prime divisions of number " << N << " are :\n";
primePoints(N);
return 0;
}
ผลลัพธ์
All prime divisions of number 2359 are : 1