[C++][算法基础]判定质数(试除法)

给定 n 个正整数 ai,判定每个数是否是质数。

输入格式

第一行包含整数 n。

接下来 n 行,每行包含一个正整数 ai。

输出格式

共 n 行,其中第 i 行输出第 i 个正整数 ai 是否为质数,是则输出 Yes,否则输出 No

数据范围

1≤n≤100,
1≤ai≤2^{31}−1

输入样例:
2
2
6
输出样例:
Yes
No

代码:

#include<iostream>
using namespace std;
int n,x;

int IsPrime(int x){
    if(x == 1 ||x == 0){
        return 0;
    }
    int flag = 1;
    for(int i = 2;i <= x / i;i++){
        if(x % i == 0){
            flag = 0;
            break;
        }
    }
    if(flag == 1){
        return 1;
    }else{
        return 0;
    }
}

int main(){
    cin>>n;
    while(n--){
        cin>>x;
        int res = IsPrime(x);
        if(res == 1){
            cout<<"Yes"<<endl;
        }else{
            cout<<"No"<<endl;
        }
    }
    return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
邻接表表示的有向图可以通过深度优先搜索(DFS)算法判定是否为有向无环图(DAG)。具体算法步骤如下: 1. 对每个节点维护三个状态:未访问(0)、正在访问(1)、已访问(2)。 2. 从任意一个未访问的节点开始深度优先遍历,每次遍历到一个节点时,将其状态设置为正在访问。 3. 对于当前节点的每个邻接节点,如果其状态是未访问,则对其进行递归访问。 4. 如果当前节点的任意邻接节点状态为正在访问,说明存在环,直接返回false。 5. 遍历完所有邻接节点后,将当前节点状态设置为已访问,返回true。 下面是具体的C++代码实现: ```c++ #include <iostream> #include <vector> using namespace std; bool dfs(vector<vector<int>>& graph, vector<int>& visited, int cur) { visited[cur] = 1; // 当前节点状态设置为正在访问 for (int next : graph[cur]) { if (visited[next] == 0) { // 邻接节点未访问,递归访问 if (!dfs(graph, visited, next)) { return false; } } else if (visited[next] == 1) { // 存在环,返回false return false; } } visited[cur] = 2; // 当前节点状态设置为已访问 return true; } bool isDAG(vector<vector<int>>& graph) { int n = graph.size(); vector<int> visited(n, 0); // 初始化所有节点状态为未访问 for (int i = 0; i < n; i++) { // 从任意一个未访问的节点开始遍历 if (visited[i] == 0) { if (!dfs(graph, visited, i)) { return false; } } } return true; } int main() { vector<vector<int>> graph = {{1, 2}, {3}, {3}, {4, 5}, {5}, {}}; if (isDAG(graph)) { cout << "The graph is a DAG." << endl; } else { cout << "The graph is not a DAG." << endl; } return 0; } ``` 上面的代码中,`graph`是邻接表表示的有向图,`visited`是节点状态数组。`dfs`函数是深度优先遍历函数,`isDAG`函数则是判断有向图是否为DAG的函数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值