modulo

How do you check whether a number is divisible by another number?

How do you check whether a number is divisible by another number? Question: I need to test whether each number from 1 to 1000 is a multiple of 3 or a multiple of 5. I tried this code in Python 2.x: n = 0 s = 0 while (n < 1001): x = n/3 if …

Total answers: 9

Cube root modulo P — how do I do this?

Cube root modulo P — how do I do this? Question: I am trying to calculate the cube root of a many-hundred digit number modulo P in Python, and failing miserably. I found code for the Tonelli-Shanks algorithm which supposedly is simple to modify from square roots to cube roots, but this eludes me. I’ve …

Total answers: 4

Find the division remainder of a number

Find the division remainder of a number Question: How could I go about finding the division remainder of a number in Python? For example: If the number is 26 and divided number is 7, then the division remainder is 5. (since 7+7+7=21 and 26-21=5.) For simple divisibility testing, see How do you check whether a …

Total answers: 13

What is the result of % in Python?

What is the result of % in Python? Question: What does the % in a calculation? I can’t seem to work out what it does. Does it work out a percent of the calculation for example: 4 % 2 is apparently equal to 0. How? Asked By: orange || Source Answers: An expression like x …

Total answers: 20

The modulo operation on negative numbers in Python

How does the modulo (%) operator work on negative numbers in Python? Question: Exactly how does the % operator work in Python, particularly when negative numbers are involved? For example, why does -5 % 4 evaluate to 3, rather than, say, -1? Asked By: facha || Source Answers: Unlike C or C++, Python’s modulo operator …

Total answers: 13

C and Python – different behaviour of the modulo (%) operation

C and Python – different behaviour of the modulo (%) operation Question: I have found that the same mod operation produces different results depending on what language is being used. In Python: -1 % 10 produces 9 In C it produces -1 ! Which one is the right modulo? How to make mod operation in …

Total answers: 6

Is & faster than % when checking for odd numbers?

Is & faster than % when checking for odd numbers? Question: To check for odd and even integer, is the lowest bit checking more efficient than using the modulo? >>> def isodd(num): return num & 1 and True or False >>> isodd(10) False >>> isodd(9) True Asked By: riza || Source Answers: Yep. The timeit …

Total answers: 9

What does the percentage sign mean in Python

What does the percentage sign mean in Python Question: In the tutorial there is an example for finding prime numbers: >>> for n in range(2, 10): … for x in range(2, n): … if n % x == 0: … print(n, ‘equals’, x, ‘*’, n//x) … break … else: … # loop fell through without …

Total answers: 8