C++ 中的素數點(將數字分成兩個素數的點)


在這個問題中,我們給定一個數字 N。我們的任務是列印數字的所有素數點,否則如果不存在素數點,則列印 -1。

素數點是指將數字分成兩個素數的索引值,一個在左邊,另一個在右邊。

讓我們舉個例子來理解這個問題

Input: 2359
Output: 1

說明:在索引 1 處分割數字。我們將得到 2 和 59 作為兩個素數。

為了解決這個問題,我們將檢查數字是否可以進行左右分割。如果有效,我們將嘗試所有可以生成的數字組合,並檢查它們是否為素數。如果它們是素數,則列印索引。

以下程式碼顯示了我們解決方案的實現

示例

 即時演示

#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 == false)
   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

更新於: 2020年2月3日

122 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.