将Python转换为C或C

将Python转换为C或C

本文介绍了将Python转换为C或C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def asallar(limit):
   limitn = limit+1
   asal_degil = [False] * limitn
   asal_listesi = []
 
   for i in range(2, limitn):
       if asal_degil[i]:
           continue
       for f in xrange(i*2, limitn, i):
           asal_degil[f] = True
       asal_listesi.append(i)
 
   return asal_listesi







a = asallar(1000000)
print a[9999]







timeit asallar(1000000)

推荐答案

#include <iostream>
using namespace std;

vector <int>  asallar(size_t limit)
{
  vector <bool> nov(limit+1, false);
  vector <int> result;
  for (size_t i=2; i<=limit; ++i)
  {
    if ( nov[i] ) continue;
    for (size_t f = i*2; f<=limit; f+=i)
    {
      nov[f] = true;
    }
    result.push_back(i);
  }
  return result;
}

int main()
{
  auto v = asallar(1000000);
}





时间:



Timing:

Python program: about 300 ms
C++ program:    about 100 ms



请注意:如果向量< int> (而不是向量< bool> )在 C ++ 程序中使用,然后执行速度加倍。


Please note: if a vector<int> (instead of a vector<bool>) is used in the C++ program, then the execution speed is doubled.


def asallar(limit): \\ void asallar(int limit, int* asal_listesi){
   limitn = limit+1 \\ int limitn =limit+1;
   asal_degil = [False] * limitn \\ int *asal_degil = malloc(...)
   asal_listesi = [] \\ vector asal_listesi; 
 
   for i in range(2, limitn): \\ for(int i=2; i<limitn;>       if asal_degil[i]: \\ if(asal_degil[i])
           continue       \\ continue;
       for f in xrange(i*2, limitn, i): \\ etc
           asal_degil[f] = True
       asal_listesi.append(i)
 
   return asal_listesi


这篇关于将Python转换为C或C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 00:18