Unit 2: Basic math operations (addition, subtraction, multiplication, division and exponentiation) - Subjective Questions
CSE329 — Prelude To Competitive Coding • Practice Questions with Detailed Answers
20 questions
Define Fast Modulo Multiplication and explain why it is needed in competitive programming. Illustrate with an example.
Fast Modulo Multiplication is a technique used to compute without causing integer overflow, even when and are very large numbers.
Why it is needed:
- When and are close to the maximum value of a data type (e.g., ), their product can overflow a 64-bit integer.
- Direct multiplication before taking modulo produces incorrect results.
Approach (Russian Peasant / Binary Multiplication):
We express multiplication as repeated addition using the binary representation of :
At each step we take modulo to keep values small.
Algorithm:
- Initialize
result = 0,a = a % m. - While
b > 0:- If
bis odd:result = (result + a) % m a = (2 * a) % mb = b / 2
- If
Example: Compute .
- , so effectively .
- Using the algorithm the result is , which matches .
This runs in time and guarantees no overflow.
Explain the technique of Exponentiation by Squaring (Exponential squaring). Derive its time complexity.
Exponentiation by Squaring is an efficient method to compute in time instead of the naive approach.
Core Idea:
We use the recursive relations:
Iterative Algorithm:
- Initialize
result = 1,base = a. - While
n > 0:- If
nis odd:result = result * base base = base * basen = n / 2
- If
Example: Compute .
- .
Time Complexity Derivation:
- Each step halves , so the number of iterations is .
- Each iteration performs a constant number of multiplications.
- Therefore the total complexity is .
This is dramatically faster than repeated multiplication for large exponents.
What is the N-th non-square number? Derive a direct formula to find it without generating all numbers.
A non-square number is a positive integer that is not a perfect square (i.e., not ).
Goal: Find the -th non-square number directly.
Derivation:
- Among the first natural numbers, the count of perfect squares is .
- So the number of non-squares up to is .
- We want the value such that it is the -th non-square.
Formula:
A commonly used simpler form is:
Explanation: The term counts how many perfect squares lie below the target, so we shift by that many positions.
Example: For :
- Result .
- Checking the sequence of non-squares: — the 5th is indeed . ✓
This gives an solution.
Define Modular Exponentiation and write an algorithm to compute efficiently.
Modular Exponentiation is the operation of computing efficiently, which is fundamental in cryptography (e.g., RSA) and number theory.
Why efficient computation is needed:
- grows extremely fast and cannot be stored directly.
- We apply modulo at each step to keep intermediate values small.
Key property:
Algorithm (Binary/Fast Modular Exponentiation):
- Initialize
result = 1,a = a % m. - While
b > 0:- If
bis odd:result = (result * a) % m b = b >> 1(integer divide by 2)a = (a * a) % m
- If
- Return
result.
Example: Compute .
- , so .
- The algorithm yields using multiplications.
Time Complexity: — logarithmic in the exponent.
Note: For very large , combine this with fast modulo multiplication to prevent overflow during .
Explain the concept of Modular Multiplicative Inverse. Under what condition does it exist?
The Modular Multiplicative Inverse of an integer under modulo is an integer such that:
It is often denoted as .
Condition for Existence:
- The inverse exists if and only if , i.e., and are coprime.
- If , no inverse exists.
Why it matters:
- Division is not directly defined in modular arithmetic. To compute , we multiply by the inverse: .
Methods to compute:
- Extended Euclidean Algorithm: Solves ; the value is the inverse. Works for any coprime .
- Fermat's Little Theorem: If is prime and , then .
Example: Inverse of modulo .
- We need .
- , so the inverse is .
Using Fermat's Little Theorem, derive the formula for the modular multiplicative inverse and demonstrate with an example.
Fermat's Little Theorem states that if is a prime and is an integer not divisible by , then:
Derivation of the Inverse:
- Starting from .
- Rewrite as .
- Comparing with the definition of inverse , we get:
Requirement: The modulus must be prime and .
Computation: We compute using fast modular exponentiation in time.
Example: Find the inverse of modulo .
- .
- .
- .
- Check: . ✓
So the inverse of modulo is .
Describe how to compute the sum of the middle row and middle column elements in a square matrix. Write the conditions and formula.
For a square matrix of odd order , the middle row and middle column are well-defined and pass through the center element.
Conditions:
- The problem is typically defined for matrices of odd dimension (so a unique middle exists).
- Middle index (integer division, 0-based indexing).
Approach:
- Let
mid = n / 2. - Sum of middle row: add all elements for to .
- Sum of middle column: add all elements for to .
- The center element is counted in both; if a combined total is needed we subtract it once.
Formula:
Example: For matrix
mid = 1.- Middle row sum .
- Middle column sum .
- Combined (subtracting center 5): .
Time Complexity: .
Explain the algorithm to check whether all rows of a matrix are circular rotations of each other.
Two arrays are circular rotations of each other if one can be obtained by rotating the other cyclically. We must verify this for every row against a reference row.
Key Idea (String Concatenation Trick):
- An array
Bis a rotation of arrayAif and only ifBis a substring ofA + A(A concatenated with itself).
Algorithm:
- Take the first row as the reference and build a string
S = row0 + row0(concatenation, using a separator to avoid false matches). - For each subsequent row
i:- Convert
row[i]into a string patternP. - Check if
Pis a substring ofSusing a pattern matching algorithm (e.g., KMP). - If
Pis not found, the rows are not all circular rotations — returnfalse.
- Convert
- If all rows pass, return
true.
Example: For matrix
- Reference doubled:
1 2 3 4 1 2 3 4. - Row 2
4 1 2 3— found as substring. ✓ - Row 3
3 4 1 2— found as substring. ✓ - Result: true.
Time Complexity: using KMP, where = number of rows, = row length.
State and explain the Inclusion-Exclusion Principle for two and three sets with a suitable example.
The Inclusion-Exclusion Principle (IEP) is a counting technique to find the size of the union of sets by adding sizes of individual sets and correcting for over-counted overlaps.
For Two Sets:
We subtract because elements in both are counted twice.
For Three Sets:
Intuition:
- Add all single sets.
- Subtract all pairwise intersections (removed double counting).
- Add back triple intersection (which was subtracted too many times).
Example: Count numbers from to divisible by or .
- Divisible by : .
- Divisible by : .
- Divisible by : .
- By IEP: .
So 67 numbers between 1 and 100 are divisible by 2 or 3.
State the Pigeonhole Principle and its generalized form. Give two real applications.
The Pigeonhole Principle states:
If items are placed into containers and , then at least one container must hold more than one item.
Generalized Pigeonhole Principle:
If items are placed into containers, then at least one container holds at least items.
Application 1 — Duplicate elements:
- Among any people, at least two share the same birth month (since there are only months). By generalized form: .
Application 2 — Subarray with sum divisible by n:
- Given an array of integers, there always exists a non-empty contiguous subarray whose sum is divisible by .
- Reason: Consider prefix sums modulo . There are possible remainders . If any prefix is , that prefix works. Otherwise, we have prefixes mapped to non-zero remainders, so by pigeonhole two prefix sums share a remainder — their difference is a subarray divisible by .
The principle is powerful for existence proofs in combinatorics.
Compare naive exponentiation with exponentiation by squaring in terms of time complexity, and explain when each is preferable.
Naive Exponentiation:
- Computes by multiplying by itself times.
- Loop runs times:
result *= a. - Time Complexity: .
Exponentiation by Squaring:
- Uses the property for even and for odd .
- Reduces the exponent by half each step.
- Time Complexity: .
Comparison Table:
| Aspect | Naive | Squaring |
|---|---|---|
| Time | ||
| Multiplications | ||
| Implementation | Very simple | Slightly complex |
| Large exponents | Slow/impractical | Efficient |
When to use each:
- Naive is fine for very small exponents (e.g., ) where simplicity matters.
- Squaring is preferred for large exponents ( up to ), cryptography, and modular exponentiation where speed is critical.
Example: For , naive needs ~ multiplications while squaring needs only ~.
Explain how the Extended Euclidean Algorithm is used to compute the modular multiplicative inverse. Trace it for finding the inverse of modulo .
The Extended Euclidean Algorithm finds integers and satisfying Bézout's identity:
Use for Inverse:
- If , then .
- Taking modulo : .
- Thus (adjusted to be positive) is the modular inverse of .
- Works for any modulus (not just primes), unlike Fermat's method.
Tracing for :
Step 1 — Euclidean division:
- → gcd = 1.
Step 2 — Back-substitution:
So for .
Step 3 — Adjust to positive: .
Check: . ✓
Therefore, .
Distinguish between the Inclusion-Exclusion Principle and the Pigeonhole Principle with respect to their purpose and typical use cases.
Both are fundamental combinatorial principles but serve very different purposes.
Inclusion-Exclusion Principle (IEP):
- Purpose: To count the exact size of the union of overlapping sets.
- Nature: A precise counting/enumeration formula.
- Formula: (and extensions).
- Typical use: Counting numbers divisible by given factors, derangements, surjections, counting problems with 'at least one' conditions.
Pigeonhole Principle:
- Purpose: To prove existence — guarantees that some condition must hold.
- Nature: An existence argument, not a counting formula.
- Statement: If items go into boxes, some box has items.
- Typical use: Proving duplicates exist, subarray sum divisibility, collision arguments, guaranteeing patterns.
Comparison Table:
| Feature | Inclusion-Exclusion | Pigeonhole |
|---|---|---|
| Goal | Exact count | Existence guarantee |
| Output | A number | A yes/no assertion |
| Answers | 'How many?' | 'Does one exist?' |
| Style | Formula-driven | Reasoning-driven |
Summary: IEP tells us how many, while Pigeonhole tells us that something must exist.
Write pseudocode for fast modulo multiplication (multiplying two large numbers under a modulus) and explain each step.
Objective: Compute safely for large (up to ~) without overflow.
Pseudocode:
function mulmod(a, b, m):
result = 0
a = a % m
while b > 0:
if (b & 1) == 1: // if lowest bit of b is set
result = (result + a) % m
a = (2 * a) % m // double a under modulo
b = b >> 1 // halve b
return result
Step-by-step explanation:
result = 0: accumulator for the final answer.a = a % m: reduce first so it stays within bounds.if b is odd: the current bit of contributes the current value of , so we add it to the result modulo .a = (2 * a) % m: shift to the next binary place (doubling), keeping it reduced.b = b >> 1: process the next bit of .
Principle: This mirrors binary multiplication:
Because we only ever add and double (never directly multiply large numbers), intermediate values stay below , avoiding overflow.
Time Complexity: .
Using the Inclusion-Exclusion Principle, find how many integers from to are divisible by , , or . Show all steps.
We need where:
- = multiples of
- = multiples of
- = multiples of
Step 1 — Individual counts:
Step 2 — Pairwise intersections (LCMs):
Step 3 — Triple intersection:
Step 4 — Apply IEP:
Answer: 734 integers from to are divisible by , , or .
Explain why applying modulo at intermediate steps gives correct results in modular arithmetic. State the key distributive properties for addition and multiplication.
In modular arithmetic, we can reduce numbers by modulo at each intermediate step without affecting the final result. This is crucial to prevent overflow and keep numbers manageable.
Key Distributive Properties:
Addition:
Subtraction:
(The ensures the result stays non-negative.)
Multiplication:
Why it works:
- Any integer can be written as where .
- When combining numbers, the terms are multiples of and vanish under modulo.
- Hence only the remainders influence the final modular result.
Important Exception — Division:
- Division does not distribute directly: .
- Instead we must multiply by the modular multiplicative inverse: .
Example: , which equals . ✓
Prove using the Pigeonhole Principle that in any group of integers chosen from , at least one pair is coprime.
Claim: If we choose any integers from the set , then at least two of them are consecutive, and consecutive integers are always coprime.
Setup — Constructing the Pigeonholes:
- Partition the numbers into pairs of consecutive integers:
- This gives exactly pairs (pigeonholes).
Applying the Pigeonhole Principle:
- We are choosing numbers (pigeons) and placing them into pairs (pigeonholes).
- Since , by the Pigeonhole Principle at least one pair must contain both its numbers among our chosen set.
- Those two numbers are consecutive integers of the form and .
Consecutive integers are coprime:
- Suppose . Then divides their difference .
- Therefore , meaning and are coprime.
Conclusion: At least one pair of the chosen integers is coprime.
Example: From (), choosing any numbers, e.g., contains consecutive pair which is coprime.
Describe a step-by-step approach to compute where is prime. Illustrate with .
Division in modular arithmetic cannot be done directly. We convert it into multiplication by the modular multiplicative inverse.
Step-by-Step Approach:
- Understand the goal: , where is the modular inverse of .
- Check condition: Since is prime and is not a multiple of , , so the inverse exists.
- Compute inverse using Fermat's Little Theorem:
Use fast modular exponentiation to compute this in . - Multiply: Compute .
Illustration — :
- Here , , (prime).
- Inverse of 5: .
- So . Check: . ✓
- Result: .
Verification: , and . ✓
Explain the significance of modular exponentiation in cryptography, particularly in the RSA algorithm.
Modular exponentiation — computing efficiently — is the computational backbone of many public-key cryptosystems, most notably RSA.
Role in RSA:
RSA relies on modular exponentiation for both encryption and decryption:
-
Key generation: Choose two large primes and , compute and . Select public exponent and private exponent such that (i.e., is the modular inverse of ).
-
Encryption: Ciphertext .
-
Decryption: Plaintext .
Why it is significant:
- Efficiency: Messages and keys involve numbers with hundreds of digits. Fast modular exponentiation () makes these operations feasible; naive methods would be impossible.
- Security (One-way function): Computing is easy, but reversing it (finding ) without the private key requires factoring into and — computationally infeasible for large . This asymmetry provides security.
- Modular inverse is used to derive the private key from .
Summary: Modular exponentiation enables the practical, fast, and secure operations that make RSA and similar cryptosystems possible. Without efficient exponentiation, public-key cryptography would not be viable.
Given a matrix, explain the special case handling and edge cases when computing the sum of the middle row and middle column, and discuss even-order matrices.
Computing the sum of the middle row and column depends heavily on whether the matrix has odd or even dimensions.
Odd-order matrix ( odd):
- A unique middle exists at index (integer division).
- The center element lies on both the middle row and middle column.
- Sum formula:
- We subtract the center once to avoid double counting.
Even-order matrix ( even):
- There is no single middle row or column; two central rows/columns exist.
- Handling options:
- Declare the operation undefined and return an error/zero.
- Consider the two middle rows (indices and ) and two middle columns, summing all four.
- The expected behavior must be clearly defined by the problem statement.
Edge Cases:
- matrix: The single element is both the middle row and column; sum .
- Non-square matrix: 'Middle row' and 'middle column' may differ; usually the problem restricts to square matrices.
- Empty matrix: Return or flag as invalid.
Example ():
- ; middle row ; middle column .
- Combined .
Time Complexity: .
Define Fast Modulo Multiplication and explain why it is needed in competitive programming. Illustrate with an example.
Fast Modulo Multiplication is a technique used to compute without causing integer overflow, even when and are very large numbers.
Why it is needed:
- When and are close to the maximum value of a data type (e.g., ), their product can overflow a 64-bit integer.
- Direct multiplication before taking modulo produces incorrect results.
Approach (Russian Peasant / Binary Multiplication):
We express multiplication as repeated addition using the binary representation of :
At each step we take modulo to keep values small.
Algorithm:
- Initialize
result = 0,a = a % m. - While
b > 0:- If
bis odd:result = (result + a) % m a = (2 * a) % mb = b / 2
- If
Example: Compute .
- , so effectively .
- Using the algorithm the result is , which matches .
This runs in time and guarantees no overflow.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →