Python中的divmod()及其应用

python中的divmod()方法接受两个数字,并返回一对由它们的商和余数组成的数字。

null

语法:

divmod(x, y)x and y : x is numerator and y is denominatorx and y must be non complex

例如:

Input : x = 9, y = 3Output :(3, 0)Input : x = 8, y = 3Output :(2, 2)

说明: divmod()方法采用两个参数x和y,其中x被视为分子,y被视为分母。该方法同时计算这两个参数 x//y x%y 并返回两个值。

  • 如果x和y是整数,则返回值为
(x // y, x % y)
  • 如果x或y是一个浮点数,结果是
(q, x % y), where q is the whole part of the quotient.

Python3

# Python3 code to illustrate divmod()
# divmod() with int
print ( '(5, 4) = ' , divmod ( 5 , 4 ))
print ( '(10, 16) = ' , divmod ( 10 , 16 ))
print ( '(11, 11) = ' , divmod ( 11 , 11 ))
print ( '(15, 13) = ' , divmod ( 15 , 13 ))
# divmod() with int and Floats
print ( '(8.0, 3) = ' , divmod ( 8.0 , 3 ))
print ( '(3, 8.0) = ' , divmod ( 3 , 8.0 ))
print ( '(7.5, 2.5) = ' , divmod ( 7.5 , 2.5 ))
print ( '(2.6, 10.7) = ' , divmod ( 2.6 , 0.5 ))


输出:

(5, 4) =  (1, 1)(10, 16) =  (0, 10)(11, 11) =  (1, 0)(15, 13) =  (1, 2)(6.0, 5) =  (2.0, 2.0)(3, 9.0) =  (0.0, 3.0)(13.5, 6.2) =  (3.0, 0.0)(1.6, 10.7) =  (5.0, 0.10000000000000009)

错误和例外

  1. 如果两个参数中的任何一个(比如x和y)是浮点,则结果是(q,x%y)。这里,q是商的全部。
  2. 如果第二个参数为0,则返回 零除法误差
  3. 如果第一个参数为0,则返回(0,0)

实际应用: 使用divmod()函数检查数字是否为素数。

例如:

Input : n = 7Output :PrimeInput : n = 15Output :Not Prime

算法

  1. 初始化一个新变量,比如用给定的整数x,变量计数器为0
  2. 运行一个循环,直到给定的整数变为0,并不断递减。
  3. 将divmod(n,x)返回的值保存在两个变量中,例如p和q
  4. 检查q是否为0,这意味着n完全可以被x整除,因此增加计数器值
  5. 检查计数器值是否大于2,如果大于,则数字不是素数,否则是素数

Python3

# Python code to find if a number is
# prime or not using divmod()
# Given integer
n = 15
x = n
# Initialising counter to 0
count = 0
while x ! = 0 :
p, q = divmod (n, x)
x - = 1
if q = = 0 :
count + = 1
if count > 2 :
print ( 'Not Prime' )
else :
print ( 'Prime' )


输出:

Not Prime

更多应用程序:

例1:

Python3

# Sum of digits of a number using divmod
num = 86
sums = 0
while num ! = 0 :
use = divmod (num, 10 )
dig = use[ 1 ]
sums = sums + dig
num = use[ 0 ]
print (sums)


输出:

14

例2:

Python3

# reversing a number using divmod
num = 132
pal = 0
while num ! = 0 :
use = divmod (num, 10 )
dig = use[ 1 ]
pal = pal * 10 + dig
num = use[ 0 ]
print (pal)


输出:

231 
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享