回复 14楼 搬砖
#include<iostream>
using namespace std;
int heads[30]={30,30,30,30,30,30,
30,30,30,30,30,30,
30,30,30,30,30,30,
30,30,30,30,30,30,
30,30,30,30,30,30};
bool IsPrime(int n)
{
if(n==0||n==1) return false;
if(n==2) return true;
int abso=n>0?n:-n;
for(int i=2;i<abso;i++)
{
if(n%i==0) return false;
}
return true;
}
void PrintNum(char*str,int last,int num)
{
int i,idx=1;
for(i=0;i<=last;i++)
{
cout<<str[i];
if(i+1==heads[idx]&&heads[idx]!=30&&idx<=num) cout<<",";
}
cout<<endl;
}
bool Divide(char*str,int from,int to,int depth)
//这个函数是核心,看它就是了。C++的
{
int i;char s[30];int idx;
if(from==to)
//最末一个字符是素数
{
heads[depth]=from;
if(IsPrime(str[from]-48))
{
PrintNum(str,to,depth);return true;
//打印得出的素数集
};//字符ascii值减48正好等于字符所显示的数字的值
}
for(i=from;i<=to&&i-from<6;i++)
{
strcpy(s,str+from);
s[i-from+1]='\0';
if(IsPrime(atoi(s)))
{
heads[depth]=from;
if(i==to)
//最末一个字符串是素数
{
PrintNum(str,to,depth);return true;
//打印结果
}
else
if(Divide(str,i+1,to,depth+1))
return true;
}
else continue;
}
return false;
}
int main()
{
char str[30];
cout<<"请输入一个不超过30位的数:"<<endl;cin>>str;
int length=strlen(str)-1;
if(Divide(str,0,length,0)) cout<<"可作素数拆分\n";
else cout<<"不可作素数拆分";
return 0;
}