简体   繁体   English

将一段C ++转换为Python

[英]Converting a piece of C++ to Python

I'm trying to convert this C++ to Python. 我正在尝试将此C ++转换为Python。 I practice Python only and haven't touched C/C++ yet. 我只练习Python,还没有接触过C / C ++。

int phi(const int n)
{
  // Base case
  if ( n < 2 )
    return 0;

  // Lehmer's conjecture
  if ( isprime(n) )
    return n-1;

  // Even number?
  if ( n & 1 == 0 ) {
    int m = n >> 1;
    return !(m & 1) ? phi(m)<<1 : phi(m);
  }

  // For all primes ...
  for ( std::vector<int>::iterator p = primes.begin();
        p != primes.end() && *p <= n;
        ++p )
  {
    int m = *p;
    if ( n % m  ) continue;

    // phi is multiplicative
    int o = n/m;
    int d = binary_gcd(m, o);
    return d==1? phi(m)*phi(o) : phi(m)*phi(o)*d/phi(d);
  }
}

Most of it is straightforward to convert, it just requires looking up C++ operators. 大多数转换都很简单,只需要查找C ++运算符即可。 However, this bit: 但是,此位:

      for ( std::vector<int>::iterator p = primes.begin();
        p != primes.end() && *p <= n;
        ++p )

What does it mean in Python? 在Python中是什么意思?

for p in primes:
  if p > n:
    break
   ...

or 要么

for p in (x for x in primes if x <= n):
   ...

Although the former will end quicker. 尽管前者将更快结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM