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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP