Modulo Magic

Modulo Magic

Hard C Operators 36 views
Explanation Complexity

Problem Statement

Test the modulo operator with negative numbers. What result will -7 % 3 give? What difference can there be between different couplings?

Input Format

An expression using modulo operator with negative numbers:
-7 % 3

Output Format

Result of the modulo operation.

Example

-7 % 3
-1 (in C / C++)

Constraints

• Integer operands

• Language-dependent behavior

Concept Explanation

The modulo operator (%) returns the remainder after division.
How the remainder is calculated depends on how division is defined in the language

Step-by-Step Explanation

1.Division is performed first:

• In C/C++, integer division truncates toward zero.

• -7 / 3 = -2 (truncated toward zero).

2.Modulo is calculated using the rule:

• a % b = a − (a / b) × b

3.Substitute values:

• -7 − (−2 × 3)

• -7 + 6

• -1

4.So the result is -1.

Concept Explanation

The modulo operator (%) returns the remainder after division.
How the remainder is calculated depends on how division is defined in the language

Step-by-Step Explanation

1.Division is performed first:

• In C/C++, integer division truncates toward zero.

• -7 / 3 = -2 (truncated toward zero).

2.Modulo is calculated using the rule:

• a % b = a − (a / b) × b

3.Substitute values:

• -7 − (−2 × 3)

• -7 + 6

• -1

4.So the result is -1.

Input / Output Format

Input Format
An expression using modulo operator with negative numbers:
-7 % 3
Output Format
Result of the modulo operation.
Constraints
• Integer operands

• Language-dependent behavior

Examples

Input:
-7 % 3
Output:
-1 (in C / C++)

Example Solution (Public)

C
#include <stdio.h>

int main() {
    int a = -7;
    int b = 3;

    printf("-7 %% 3 = %dn", a % b);
    printf("-7 / 3 = %dn", a / b);

    return 0;
}

Official Solution Code

#include <stdio.h>

int main() {
    int a = -7;
    int b = 3;

    printf("-7 %% 3 = %dn", a % b);
    printf("-7 / 3 = %dn", a / b);

    return 0;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.