您的位置:首页 > 其它

编写一个程序,将小于n的所有质数找出来。

2016-04-18 09:49 423 查看
c#实现如下:http://www.nowcoder.com/profile/454285/test/3057105/36326#summary

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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: