编写一个程序,将小于n的所有质数找出来。
2016-04-18 09:49
423 查看
c#实现如下:http://www.nowcoder.com/profile/454285/test/3057105/36326#summary
c++如下:
using System; using System.Collections.Generic; namespace ceshi { class taotao { static List<int> array = new List<int>(); static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("小于{0}的所有指数如下:", n); Prime(n); foreach (var item in array) { Console.WriteLine(item); } } static void Prime(int n) { for(int i = 0; i < n; i++) { if (i <= 1) continue; if (i == 2) { array.Add(i); continue; } for (int j = 2; j < Math.Sqrt(i) /*&& i % j == 0*/; j++) { if (i % j == 0) break; array.Add(i); } } } } }
c++如下:
#include<iostream> // #include <vector> #include <cmath> using namespace std; bool isPrime(int x) { if(x <= 1)return false; if(x == 2) return true; for (int i = 2; i <= sqrt((float)x); ++i) { if(x % i == 0)return false; } return true; } vector<int> getAllPrimes(int n) { vector<int> res; if(n < 2) return res; for(int i = 2; i < n; ++i) { if(isPrime(i)) { res.push_back(i); } } return res; } void main() { int n; cin>>n; // vector<int> result = getAllPrimes(n); for(int i = 0; i < result.size(); i++) { cout<<result[i]<<endl; } system("pause"); }
相关文章推荐
- Java NIO 之一 I/O基本概念
- Android中刷新列表
- ERROR:格式化hdfs后,datanode只启动了一个
- 费用最少的一款赛门铁克SSL证书
- Spring请求参数为一个数组
- 每天laravel-20160718|Command-2
- 2016.04.18,英语,《Vocabulary Builder》Unit 15
- 存储过程
- iWS工作流加载顺序
- 每天laravel-20160718|Command-2
- render和redirect_to区别
- linux centos DNS 只有主服务器的实验
- shell 编程空格注意事项
- java性能优化常用技巧
- ArrayList和LinkedList的区别
- 解决AndroidStudio SDK更新问题
- mysql启动报错 The server quit without updating PID file (/[FAILED]ql/cc.pid).
- java 的 @Override
- sock编程常见的错误
- Java 冒泡排序