top1编程
← 返回题目
题解

【基础】求无暇素数

1 条题解

  • 0
    @ 2026-7-30 1:10:01

    解题思路

    枚举候选数并逐个判断其因数,保留满足题意的素数。

    参考代码

    // 读取题目给出的数据。
    // 按照题意完成计算。
    // 这道题的做法:先读入题目给出的数据,再用简单的循环和判断完成要求。
    #include <bits/stdc++.h>
    using namespace std;
    int zhishu(int b)
    {
    	if(b <= 1)
    	{
    		return false;
    	}
    	for(int i = 2; i < b; i++)
    	{
    		if(b % i == 0)
    		{
    			return false;
    		}
    	}
    	return true;
    
    
    }
    int main(){
    	 char s[30];
    		int t,x,f=0;
    		cin>>s;
    		for(int i=0;i<strlen(s)-1;i++){
    			t=(s[i]-'0')*10+s[i+1]-'0';
    			x=(s[i+1]-'0')*10+s[i]-'0';
    			if(zhishu(t)&&zhishu(x)){
    				if(f==0){
    					cout<<t;
    					f++;
    				}else{
    					cout<<","<<t;
    				}
    			}
    		}
    	
    	return 0;
    }
    

    复杂度

    代码只使用了简单变量、循环和判断。若循环检查了 n 个数据,时间复杂度通常为 O(n);没有开辟与输入规模相关的额外数组时,空间复杂度为 O(1)。

    • 1