近日,看到有关Python的介绍,感觉不错,抽空学习了一下。都说,Python执行效率低,于是设计了一个求素数的程序,和C#、C++进行了一下比较。三个程序算法一样。Python和C#都用 List实现,C++用 Vector实现。代码如下:
Python
prime=[]
n=int(input("请输入一个整数:\n"))
from time import clock as now
start = now()
for i in range(2,n+1):
prime.append(i)
count =len(prime)
for priner in range(0,count):
if(priner<count):
if (prime[priner] * prime[priner] < prime[-1]):
curNum = prime[priner];
for s in range(priner+1,count):
if(s<count):
if (prime[s] % curNum == 0):
prime.remove(prime[s])
s=s-1
count=count-1
finish = now()
print ("运行时间%f"%((finish-start)*1000))
print("总共有%d个素数"%count)
C#
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Diagnostics;
namespace 求素数Csharp版
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
Console.WriteLine("请输入一个整数:");
int n =Convert.ToInt32( Console.ReadLine());
List<int> prime = new List<int>(n);
sw.Start();
for (int i = 2; i <= n; i++)
{
prime.Add(i);
}
int piner=0;
int count = prime.Count;
for (; piner < count; piner++)
{
if (prime[piner] * prime[piner] < prime[count-1])
{
int curNum = prime[piner];
for (int s = piner + 1; s < count;s++ )
{
if (prime[s] % curNum == 0)
{
prime.RemoveAt(s);
s--;
count--;
continue;
}
}
}
}
sw.Stop();
Console.Write("{0}以内的素数有: ",n);
Console.WriteLine("总共有{0}个素数",count);
Console.WriteLine("总运行时间:" +sw.ElapsedMilliseconds);
}
}
}
C++
#include <iostream>
#include "vector"
#include <time.h>
using namespace std;
int main(void)
{
double start, end;
cout<<"请输入一个整数: "<<endl;
int n;
cin>>n;
vector<int> prime;
vector<int>::iterator it;
for(int i=2; i<=n; i++)
{
prime.push_back(i);
}
it=prime.begin();
start =(double)clock();
for(; it<prime.end(); it++)
{
if((*it)*(*it)<*(prime.end()-1))
{
vector<int>::iterator pin=it+1;
for(; pin<prime.end(); pin++)
{
if(*(pin)%(*it)==0)pin= prime.erase(pin);
}
}
}
end =(double)clock();
int length=prime.size();
cout<<"总共有"<<length<<"个素数"<<endl;
cout<<"循环时间"<<end-start<<endl;
return 0;
}
运行结果如下:单位ms
cpython:
C#:
C++:
IronPython:
可以看出来,C#和C++运行结果比较接近,C#的效率还是不错的。Python的运行效率确实比较低,不过在IronPython中运行会提速不少。本人机器较老,以上数据只作为横向比较参考。