//***************************
//计算素数
//***Michael Wang 20180310
#include <iostream>
#include <vector>
using namespace std;
const bool isPrime(const int n)
{
//1不是素数
if (n <= 1)
{
return false;
}
for (size_t i = 2; i < n; i++)
{
if (n%i == 0)
{
return false;
}
}
return true;
}
void main()
{
int m = 100;
int num = 0;
vector<int> primes;
primes.clear();
cout << "计算100以内的素数" << endl;
for (size_t i = 2; i < m; i++)
{
if (isPrime(i))
{
num++;
primes.push_back(i);
}
}
for each (int var in primes)
{
cout << var << endl;
}
cout <<"primes.size is " << primes.size() << endl;
printf("------------------------------------\n");
for (auto j : primes)
{
cout << j << endl;
}
cout << "100以内的素数为" << num << endl;
getchar();
}
import array
def isPrime(n):
if n <= 1:
return False
for i in range(2, n):
if n%i == 0:
return False
return True
m = 2
num = 0
arrayPrimes = []
while m < 100:
if isPrime(m):
num += 1
#print(u'第%d个素数 是%d' % (num, m))
arrayPrimes.append(m)
m += 1
#遍历素数数组并输出元素和对应的索引值
for i in range( len(arrayPrimes) ):
print(i, arrayPrimes[i])
print('------------------------------------')
for index, value in enumerate(arrayPrimes):
print(index, value)
print('------------------*------------------')
for j in arrayPrimes:
print(j)
print(u'100以内总共有%d个素数\n'% num)