Given a function f(n) = (13 + 23 + 33 + … + n3), the task is to find the value of f(n) mod 4 for a given positive integer ‘n’.
Input: n=6 Output: 1 Explanation: f(6) = 1+8+27+64+125+216=441 f(n) mod 4=441 mod 4 = 1 Input: n=4 Output: 0 Explanation: f(4)=1+8+27+64 = 100 f(n) mod 4 =100 mod 4 = 0
While solving this problem, you might directly compute (13 + 23 + 33 + … + n3) mod 4. But this requires O(n) time. We can use direct formula for sum of cubes, but for large ‘n’ we may get f(n) out of range of long long int.
Here’s an efficient O(1) solution:
From division algorithm we know that every integer can be expressed as either 4k, 4k+1, 4k+2 or 4k+3.
(4k)3 = 64k3 mod 4 = 0.
(4k+1)3 = (64k3 + 48k2 + 12k+1) mod 4 = 1
(4k+2)3 = (64k3+64k2+48k+8) mod 4 = 0
(4k+3)3 = (64k3+184k2 + 108k+27) mod 4 = 3
and ((4k)3+(4k+1)3+(4k+2)3+(4k+1)4) mod 4 = (0 + 1+ 0 + 3) mod 4 = 0 mod 4
Now let x be the greatest integer not greater than n divisible by 4. So we can easily see that,
(13+23+33…..+x3) mod 4=0.
- if n is a divisor of 4 then x=n and f(n) mod 4 =0.
- Else if n is of the form 4k + 1, then x= n-1. So, f(n)= 13 + 23 + 33…..+ x3+n3) mod 4 = n^3 mod 4 = 1
- Similarly if n is of the form 4k+2 (i.e x=n-2), we can easily show that f(n) = ((n-1)3+n3) mod 4=(1 + 0) mod 4 = 1
- And if n is of the form 4k+3 (x=n-3). Similarly, we get f(n) mod 4 = ((n-2)3+(n-1)3+n3) mod 4 = (1+0+3) mod 4 = 0
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n
- Find value of (1^n + 2^n + 3^n + 4^n ) mod 5
- Find value of y mod (2 raised to power x)
- Count number of solutions of x^2 = 1 (mod p) in given range
- Find power of power under mod of a prime
- How to compute mod of a big number?
- Trick for modular division ( (x1 * x2 .... xn) / b ) mod (m)
- Divide two integers without using multiplication, division and mod operator | Set2
- Minimum steps to reach end from start by performing multiplication and mod operations with array elements
- Find (1^n + 2^n + 3^n + 4^n) mod 5 | Set 2
- Find the maximum possible value of the minimum value of modified array
- Find minimum value of y for the given x values in Q queries from all the given set of lines
- Minimum value possible of a given function from the given set
- Minimum change in given value so that it lies in all given Ranges
- Find the maximum value of Y for a given X from given set of lines
- Find the XOR of the elements in the given range [L, R] with the value K for a given set of queries
- Find the sum of all the terms in the n-th row of the given series
- Find the last digit of given series
- Number of terms in Geometric Series with given conditions
- Program to find Nth term in the given Series