Python如何实现模运算? [英] How does Python implement the modulo operation?

查看:175
本文介绍了Python如何实现模运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python中%运算符的时间和空间复杂性感到好奇.另外,Python是否对% 2使用按位运算?

I'm curious in regards to the time and space complexities of the % operator in Python. Also, does Python use a bitwise operation for % 2?

修改: 我在问Python 2.7的实现,以防它与Python 3略有不同

I'm asking about Python 2.7's implementation, just in case it differs slightly from that of Python 3

推荐答案

Python使用Knuth的计算机编程艺术"中的经典算法D.运行时间(通常)与两个数字的长度的乘积成正比.空间与两个数字的长度之和成比例.

Python uses the classic Algorithm D from Knuth's 'The Art of Computer Programming'. The running time is (generally) proportional to the product of lengths of the two numbers. Space is proportional to the sum of the lengths of the two numbers.

实际的除法发生在Objects/longobject.c中,请参见 x_divrem().有关Python long的内部表示的背景,请参见Include/longintrepr.h.

The actual division occurs in Objects/longobject.c, see x_divrem(). For background on the internal representation of a Python long, see Include/longintrepr.h.

% 2不使用按位运算.用于检查数字是否为偶数/奇数的标准习惯用法是& 1.

% 2 does not use bitwise operations. The standard idiom for checking if a number is even/odd is & 1.

Python 2和3使用相同的算法.

Python 2 and 3 use the same algorithm.

这篇关于Python如何实现模运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆