Factorial remainder - factorial

Given a number n,the problem is to find all x (1<=x<=n), such that (x-1)! ie (factorial of (x-1)) leaves a remainder of x-1 when divided by x.I have tried of a dynamic programming solution where dp[n] gives the number of such numbers for given n,but finding the factorial doesn't seem to work for large numbers.Can we use modular arithmetic properties to solve this?

When (x-1)! is divided by (x-1) for x > 1, the remainder will always be 0. Since it's given that the remainder is x, you need to find all x such that x is congruent to 0 modulo x-1. (Notice that x itself is congruent to 1 mod x - 1).

Related

Find Minimum Operand to Maximize sum of bitwise AND operator

Given an array of integers Arr and an integer K, bitwise AND is to be performed on each element A[i] with an integer X
Let Final sum be defined as follows:
Sum of ( A[i] AND X ) for all values of i ( 0 to length of array-1 )
Return the integer X subject to following constraints:
Final sum should be maximum
X should contain exactly K bits as 1 in its binary representation
If multiple values of X satisfy the above conditions, return the minimum possible X
Input:
Arr : [8,4,2]
K = 2
Output: X=12
12 Contains exactly 2 bits in its binary and is the smallest number that gives maximum possible answer for summation of all (A[i] AND X)
Approach Tried :
Took bitwise OR for all numbers in the array in binary and retained the first K bits of the binary that had 1 , made remaining bits 0, convert back to int
Passed 7/12 Test Cases
Can someone help me out with what mistake am I making with regards to the approach or suggest a better approach ? Thanks in advance.
Consider an input like [ 8, 4, 4, 4 ], K = 1. Your algorithm will give 8 but the correct answer is 4. Just because a given bit is more significant doesn't mean that it will automatically contribute more to the sum, as there might be more than twice as many elements of the array that use a smaller bit.
My suggestion would be to compute a weight for each bit of your potential X -- the number of elements of the array that have that bit set times the value of that bit (2i for bit i). Then find the K bits with the largest weight.
To do this, you need to know how big your integers are -- if they are 32 bits, you need to compute just 32 weights. If they might be bigger you need more. Depending on your programming language you may also need to worry about overflow with your weight calculations (or with the sum calculation -- is this a true sum, or a sum mod 2n for some n?). If some elements of the array might be negative, how are negatives represented (2s complement?) and how does that interact with AND?
Let dp[k][i] represent the maximum sum(a & X), a ∈ array, where i is the highest bit index in X and k is the number of bits in X. Then:
dp[1][i]:
sum(a & 2^i)
dp[k][i]:
sum(a & 2^i) + max(dp[k-1][j])
for j < i
sum(a & 2^i) can be precalculated for all values of i in O(n * m), where m is the word size. max(dp[k-1][j]) is monotonically increasing over j and we want to store the earliest instance of each max to minimise the resulting X.
For each k, therefore, we iterate over m is. Overall time complexity O(k * m + n * m), where m is the word size.

Fixed point code division understanding

Code for division by 9 in fixed point.
1. q = 0; // quotient
2. y = (x << 3) - x; // y = x * 7
3. while(y) { // until nothing significant
4. q += y; // add (effectively) binary 0.000111
5. y >>= 6; // realign
6. }
7. q >>= 6; // align
Line 2 through 5 in the FIRST execution of while loop is effectively doing
x*.000111 (in decimal representation x*0.1), what it is trying to achieve in subsequent while loops?
Should it not be again multiplying that with 7 and again shifting instead
of doing only shifting to take care of recurrence?
Explanation with respect to plain decimal number multiplication as to what is being achieved with only shifting would be nice.
Detailed code explanation here:
Divide by 9 without using division or multiplication operator
Lets denote 7/64 by the letter F. 7/64 is represented in binary as 0.000111 and is very close to 1/9. But very close is not enough. We want to use F to get exactly to 1/9.
It is done in the following way
F+ (F/64) + (F/64^2) + (F/64^3) + (F/64^4)+ (F/64^5) + ...
As we add more elements to this sequence the results gets closer to 1/9
Note each element in the sequence is exactly 1/64 from previous element.
A fast way to divide by 64 is >>6
So effectively you want to build a loop which sums this sequence. You start from F and in each iteration do F>>6 and add it to the sum.
Eventually (after enough iterations) the sum will be exactly 1/9.
Ok now, you are ready to understand the code.
Instead of using F (which is a fraction and cannot be represented in fixed points) the code multiplies F by x.
So the sum of the sequence will be X/9 instead of 1/9
Moreover in order to work with fixed points it is better to store 64*X*F and the result would by 64*X/9.
Later after the summation we can divide by 64 to get the X/9
The code stores in the variable y the value of F*x*64
variable q stores the sum of the sequence. In each loop iteration we generate the next element in the sequence by dividing the previous element by 64 (y>>=6)
Finally after the loop we divide the sum by 64 (q>>=6) and get the result X/9.
Regarding you question. We should not multiply by 7 each time or else we will get a sum of the sequence of
F+ (F^2) + (F^3) + (F^4) + (F^5)...
This would yield a result of ~X/(8+1/7) instead of X/9.
Shifting by one to the left multiplies by two, shifting by one to the right divides by two. Why?
Shifting is the action of taking all the bits from your number and moving them n bits to the left/right. For example:
00101010 is 42 in Binary
42 << 2 means "shift 42 2 bits to the left" the result is
10101000 which is 168 in Binary
we multiplied 42 by 4.
42 >> 2 means "shift 42 2 bits to the right" the result is
00001010 which is 10 in binary (Notice the rightmost bits have been discarded)
we divided 42 by 4.
Similarly : (x << 3) is x * 8, so (x << 3) - x is (x * 8) - x => x * 7

A numbers power between 0 and 1 in C

I'm making a program to replace math.h's pow() function.
I'm not using any functions from math.h.
The problem is, I can calculate powers as integers like
15-2
45.3211
but I can't calculate
x2.132
My program first finds integer power of x (x2) and multiplies it by (x0.132).
I know that x0.132 is 1000th root of x to the power 132 but I can't solve it.
How can I find xy (0 < y < 1)
To compute x ^ y, 0 < y < 1 :
Approximate y as a rational fraction, (a/b)
(Easiest way: Pick whatever b you want to get sufficient accuracy as a constant.
Then use: a = b * y.)
Approximate the b root of y using any method you like, such as Newton's.
(Simplest way: You know it's between 0 and b and can easily tell if a given value is too low or too high. So keep a min that starts at zero and a max that starts at b. Repeatedly try (min + max) / 2, see if it's too big or too small, and adjust min or max appropriately. Repeat until min and max are nearly the same.)
Raise that to the a power.
(Possibly by repeatedly multiplying it by itself. Optimize this if you like. For example, a^4 can be computed with just two multiplications, one to find a^2 and then one to square it. This generalizes easily.)
Use the factorization inherent in floating point formats to split x=2^e*m with 1<=m<2 to create the sub-problems 2^(e*y) and m^y
Use square roots, x^y=sqrt(x)^(2*y) and if there is an integer part in 2*b, split that off.
Use the binomial theorem for x close to 1, which will occur when iterating the square root.
(1+h)^y=1+y*h+(y*(y-1))/2*h^2+...+binom(y,j)*h^j+...
where the quotient from one term to the next is (y-j)/(j+1)*h
h=x-1;
term = y*h;
sum = 1+term;
j=1;
while(1+term !=1) {
term *= h*(y-j)/(1+j);
sum += term;
j+=1;
}

Why is the behavior of the modulo operator (%) different between C and Ruby for negative integers?

I was running some code in here. I tried -40 % 3. It gives me the output 2. when I performed the same operation in C, I get:
int i = (-40) % 3
printf("%d", i);
output is
-1
How are both languages performing the modulo operation internally?
Wiki says:
Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) is the remainder of the Euclidean division of a by n.
.... When either a or n is negative, the naive definition breaks down and programming languages differ in how these values are defined.
Now the question is why -40 % 3 is 2 in Ruby or in other words what is the mathematics behind it ?
Let's start with Euclidean division which states that:
Given two integers a and n, with n ≠ 0, there exist unique integers q and r such that a = n*q + r and 0 ≤ r < |n|, where |n| denotes the absolute value of n.
Now note the two definitions of quotient:
Donald Knuth described floored division where the quotient is defined by the floor function q=floor(a/n) and the remainder r is:
Here the quotient (q) is always rounded downwards (even if it is already negative) and the remainder (r) has the same sign as the divisor.
Some implementation define quotient as:
q = sgn(a)floor(|a| / n) whre sgn is signum function.
and the remainder (r) has the same sign as the dividend(a).
Now everything depends on q:
If implementation goes with definition 1 and define q as floor(a/n) then the value of 40 % 3 is 1 and -40 % 3 is 2. Which here seems the case for Ruby.
If implementation goes with definition 2 and define q as sgn(a)floor(|a| / n), then the value of 40 % 3 is 1 and -40 % 3 is -1. Which here seems the case for C and Java.
In Java and C, the result of the modulo operation has the same sign as the dividend, hence -1 is the result in your example.
In Ruby, it has the same sign as the divisor, so +2 will be the result according to your example.
In the ruby implementation, when the numerator is negative and the denominator is positive, the question that the modulo operator answers is, "What is the smallest positive number that when subtracted from the numerator, allows the denominator to divide evenly into the result?"
In all implementations, when the numerator and denominator are both positive, the question being answered is, "What is the smallest positive number that when subtracted from the numerator, allows the denominator to divide evenly into the result?"
So you can see that the ruby implementation is consistently answering the same question, even if the result is non-intuitive at first.

how to calculate modulus division

I am stuck in a program while finding modulus of division.
Say for example I have:
((a*b*c)/(d*e)) % n
Now, I cannot simply calculate the expression and then modulo it to n as the multiplication and division are going in a loop and the value is large enough to not fit even in long long.
As clarified in comments, n can be considered prime.
I found that, for multiplication, I can easily calculate it as:
((a%n*b%n)%n*c%n)%n
but couldn't understand how to calculate the division part then.
The problem I am facing is say for a simple example:
((7*3*5)/(5*3)) % 11
The value of above expression would be 7
but if I calculate the multiplication, modulo, it would be like:
((7%11)*(3%11))%11 = 10
((10%11)*(5%11))%11 = 6
now I am left with 6/15 and I have no way to generate correct answer.
Could someone help me. Please make me understand the logic by above example.
Since 11 is prime, Z11 is a field. Since 15 % 11 is 4, 1/15 equals 3 (since 3 * 4 % 11 is 1). Therefore, 6/15 is 6 * 3 which is 7 mod 11.
In your comments below the question, you clarify that the modulus will always be a prime.
To efficiently generate a table of multiplicative inverses, you can raise 2 to successive powers to see which values it generates. Note that in a field Zp, where p is an odd prime, 2p-1 = 1. So, for Z11:
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 5
2^5 = 10
2^6 = 9
2^7 = 7
2^8 = 3
2^9 = 6
So the multiplicative inverse of 5 (which is 24) is 26 (which is 9).
So, you can generate the above table like this:
power_of_2[0] = 1;
for (int i = 1; i < n; ++i) {
power_of_2[i] = (2*power_of_2[i-1]) % n;
}
And the multiplicative inverse table can be computed like this:
mult_inverse[1] = 1;
for (int i = 1; i < n; ++i) {
mult_inverse[power_of_2[i]] = power_of_2[n-1-i];
}
In your example, since 15 = 4 mod 11, you actually end up with having to evaluate (6/4) mod 11.
In order to find an exact solution to this, rearrange it as 6 = ( (x * 4) mod 11), which makes clearer how the modulo division works.
If nothing else, if the modulus is always small, you can iterate from 0 to modulus-1 to get the solution.
Note that when the modulus is not prime, there may be multiple solutions to the reduced problem. For instance, there are two solutions to 4 = ( ( x * 2) mod 8): 2 and 6. This will happen for a reduced problem of form:
a = ( (x * b) mod c)
whenever b and c are NOT relatively prime (ie whenever they DO share a common divisor).
Similarly, when b and c are NOT relatively prime, there may be no solution to the reduced problem. For instance, 3 = ( (x * 2) mod 8) has no solution. This happens whenever the largest common divisor of b and c does not also divide a.
These latter two circumstances are consequences of the integers from 0 to n-1 not forming a group under multiplication (or equivalently, a field under + and *) when n is not prime, but rather forming simply the less useful structure of a ring.
I think the way the question is asked, it should be assumed that the numerator is divisible by the denominator. In that case the finite field solution for prime n and speculations about possible extensions and caveats for non-prime n is basically overkill. If you have all the numerator terms and denominator terms stored in arrays, you can iteratively test pairs of (numerator term, denominator term) and quickly find the greatest common divisor (gcd), and then divide the numerator term and denominator term by the gcd. (Finding the gcd is a classical problem and you can easily find a simple solution online.) In the worst case you will have to iterate over all possible pairs but at some point, if the denominator indeed divides the numerator, then you'll eventually be left with reduced numerator terms and all denominator terms will be 1. Then you're ready to apply multiplication (avoiding overflow) the way you described.
As n is prime, dividing an integer b is simply multiplying b's inverse. That is:
(a / b) mod n = (a * inv(b)) mod n
where
inv(b) = (b ^ (n - 2)) mod n
Calculating inv(b) can be done in O(log(n)) time using the Exponentiation by squaring algorithm. Here is the code:
int inv(int b, int n)
{
int r = 1, m = n - 2;
while (m)
{
if (m & 1) r = (long long)r * b % n;
b = (long long)b * b % n;
m >>= 1;
}
return r;
}
Why it works? According to Fermat's little theorem, if n is prime, b ^ (n - 1) mod n = 1 for any positive integer b. Therefore we have inv(b) * b mod n = 1.
Another solution for finding inv(b) is the Extended Euclidean algorithm, which needs a bit more code to implement.
I think you can distribute the division like
z = d*e/3
(a/z)*(b/z)*(c/z) % n
Remains only the integer division problem.
I think the problem you had was that you picked a problem that was too simple for an example. In that case the answer was 7 , but what if a*b*c was not evenly divisible by c*d ? You should probably look up how to do division with modulo first, it should be clear to you :)
Instead of dividing, think in terms of multiplicative inverses. For each number in a mod-n system, there ought to be an inverse, if certain conditions are met. For d and e, find those inverses, and then it's all just multiplying. Finding the inverses is not done by dividing! There's plenty of info out there...

Resources