负数取模怎么算, -10 % 3 = ?

负数取模怎么算, -10 % 3 = ?

简介:
今天遇到了一个很奇怪的问题:-10 % 3 = ?和 10 % -3 = ?,相信很多人都跟我一样脱口而出-10 % 3 = -1,10 % -3 = 1,然后我用计算器算了一下,结果让我很惊讶,-10 % 3 = 2,10 % -3 = -2。于是我用Java执行了两个式子,算出来的结果跟我一开始想的一样的,这怎么回事呢,经过查资料发现原来每一种语言算出来的结果可能都不一样。

在这里插入图片描述
关于取模操作,WIKI里是这么定义的:https://en.wikipedia.org/wiki/Modulo_operation
In mathematics, the result of the modulo operation is an equivalence class, and any member of the class may be chosen as representative; however, the usual representative is the least positive residue, the smallest nonnegative integer that belongs to that class, i.e. the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language or the underlying hardware.

In nearly all computing systems, the quotient q and the remainder r of a divided by n satisfy:
在这里插入图片描述
However, this still leaves a sign ambiguity if the remainder is nonzero: two possible choices for the remainder occur, one negative and the other positive, and two possible choices for the quotient occur. Usually, in number theory, the positive remainder is always chosen, but programming languages choose depending on the language and the signs of a or n.

r = a - nq,而q的计算主要有:

  1. truncated division,定义如下:

q = t r u n c ( a n ) q=trunc(\frac{a}{n}) q=trunc(na)
相当于截去小数部分。3 / 2 = 1,-3 / 2 = -1

  1. Donald Knuth提出的 floored division

q = ⌊ a n ⌋ q=⌊\frac{a}{n}⌋ q=na
向下取整。3 / 2 = 1,-3 / 2 = -2

  1. Euclidean division
    q = ⌊ a n ⌋ , n > 0 q=⌊\frac{a}{n}⌋,n > 0 q=nan>0
    q = ⌈ a n ⌉ , n < 0 q = ⌈\frac{a}{n}⌉,n < 0 q=nan<0

不同程序设计语言实现的方式可能不同。

1. C/Java的处理方式:
大多数语言的处理方式都与 C/Java 一致,采用了 truncate 除法。

10 % (-3)= 1 的计算结果如下:r = 10 - (10 / -3) * -3 = 10 - (-3 x -3) = 1
-10 % 3 = -1 的计算结果如下:r = -10 - (-10 / 3) * 3 = -10 - (-3 * 3) = -1。

在这里插入图片描述

2. Python的处理方式:
Python 语言除法采用的是 floor 除法。

10 % (-3)= -2 的计算结果如下:r = 10 - (10 / -3) * -3 = 10 - (-4 x -3) = -2
-10 % 3 = 2 的计算结果如下:r = -10 - (-10 / 3) * 3 = -10 - (-4 * 3) = 2。

在这里插入图片描述

  • 28
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值