This is a question on division algorithm. Consider polynomial f=-4x^4y^2z^2+y^6+3z^5 and polynomials G={y^6-z^5, x*z-y^2, x*y^4-z^4, x^2*y^2-z^3 *x^3-z^2}.
How can you factor f with respect to G computationally such that the linear combination f=\sum_i C_i*G_i is satisfied?
I know that the remainder is zero but not which are the coefficients C_i in the above formula, example with Macaulay2
This can be related to the more general mathematical question about ideals here.
This is a very late response. You probably already have the answer, but here it is anyway. "//" computes the coefficients using the division algorithm.
R=QQ[x,y,z,MonomialOrder=>Lex];
f=-4*x^2*y^2*z^2+y^6+3*z^5;
I=ideal(x*z-y^2,x^3-z^2);
G=gb(I);
f//(gens G)
o5 = {6} | 0 |
{2} | 3x2z2-xy2z-y4 |
{5} | 0 |
{4} | 0 |
{3} | -3z3 |
So
f=-4*x^2*y^2*z^2+y^6+3*z^5
=0*(y^6-z^5)+(3*x^2*z^2-x*y^2*z-y^4)(xz-y^2)+0*(xy^4-z^4)+0(x^2*y^2-z^3)+(-3*z^3)*(x^3-z^2).
Another tip is to copy and paste your code, so that others can copy and paste it. If you post an image then we have to type it out manually. If you put four spaces before each line then it will appear as code, as I have done here.
Maybe it's enough to just do a repeated polynomial division, something
like this (a rough pseudo code..)
order G lexicographically
total_rest = 0
coefficients = {g[0]:None, g[1]:None,...}
while f > 0:
for g in G:
quotient, reminder = f / g # polynomial division
coefficients[g] += quotient
if reminder == 0:
return # We are done. f was devisible by G.
f = reminder
total_rest += lt(f) # lt: leading term
f -= lt(f)
# Now it should hold that
# f = coefficient[g]*g + ... + total_rest
Related
Im trying to understand the maths in a RSA asymetric keys generation. I founded few articles in the web, and my idea is not very clear, so i came here with the hope to finally be able to complete an example.
I understand very well maths, but im a bit confused with the steps so i will go step by step until I understand.
I will try this example with numbers lower than 16[0..15] (4bits)
To encrypt/decript the message: "hello world"
Step 1: Select 2 randomly prime numbers
P= 11
Q= 5
Step 2: Calculate H [(P-1)*(Q-1)]
H = (11-1) * (5-1) = 10* 4= 40
Step 3: Select a random prime number lower than H (E) (I believe coprimes of H also works for E)
E = 7
And now?
We can continue from step 2:
Step 3) Select E such that Greatest Common Divisor(H,E)=1 and (1 < E < H)
In your example we have gcd(40,?)=1 and 1<?<40 --> 7 satisfies this, so we choose E=7
Step 4) Compute d such that (dE) mod H =1 and d<H
In the example we have (d*7) mod 40=1 and d< 40 so we get d= 23
Step 5) public key is {E,n} and private key is {d,n} in which n = P * Q.
In the example we have the public key={7,55} and the private key={23,55}
Step 6) Compute C= M^E(mod n) for encrypting in which M is the numerical representation of the message we want to encrypt.
In the example, we have to interpret M="hello world" as a number. Here, I assume it is equal to 39 for keeping it simple (this number should be less than n). You can refer to here to know more about how to encode a text to a numeric value.
C= 39 ^7 mod 55 = 19 (encrypted value of M)
Step 7) Compute M= C^d(mod n) for decrypting 19
In the example, we have M=19^23 mod 55 = 39 (the Message which should be decoded to "hello world").
I know I need to use the extended euclidean algorithm, but I'm not sure exactly what calculations I need to do. I have huge numbers. Thanks
Well, d is chosen such that d * e == 1 modulo (p-1)(q-1), so you could use the Euclidean algorithm for that (finding the modular multiplicative inverse).
If you are not interested in understanding the algorithm, you can just call BigInteger#modInverse directly.
d = e.modInverse(p_1.multiply(q_1))
Given that, p=11, q=7, e =17, n=77, φ (n) = 60 and d=?
First substitute values from the formula:-
ed mod φ (n) =1
17 d mod 60 = 1
The next step: – take the totient of n, which is 60 to your left hand side and [e] to your right hand side.
60 = 17
3rd step: – ask how many times 17 goes to 60. That is 3.5….. Ignore the remainder and take 3.
60 = 3(17)
Step 4: – now you need to balance this equation 60 = 3(17) such that left hand side equals to right hand side. How?
60 = 3(17) + 9 <== if you multiply 3 by 17 you get 51 then plus 9, that is 60. Which means both sides are now equal.
Step 5: – Now take 17 to your left hand side and 9 to your right hand side.
17 = 9
Step 6:- ask how many times 9 goes to 17. That is 1.8…….
17 = 1(9)
Step 7:- Step 4: – now you need to balance this 17 = 1(9)
17 = 1(9) + 8 <== if you multiply 1 by 9 you get 9 then plus 8, that is 17. Which means both sides are now equal.
Step 8:- again take 9 to your left hand side and 8 to your right hand side.
9 = 1(8)
9 = 1(8) + 1 <== once you reached +1 to balance your equation, you may stop and start doing back substitution.
Step A:-Last equation in step 8 which is 9 = 1(8) + 1 can be written as follows:
1.= 9 – 1(8)
Step B:-We know what is (8) by simple saying 8 = 17 – 1(9) from step 7. Now we can re-write step A as:-
1=9 -1(17 – 1(9)) <== here since 9=1(9) we can re-write as:-
1=1(9)-1(17) +1(9) <== group similar terms. In this case you add 1(9) with 1(9) – that is 2(9).
1=2(9)-1(17)
Step C: – We know what is (9) by simple saying 9 = 60 – 3(17) from step 4. Now we can re-write step B as:-
1=2(60-3(17) -1(17)
1=2(60)-6(17) -1(17) <== group similar terms. In this case you add 6(17) with 1(17) – that is 7(17).
1=2(60)-7(17) <== at this stage we can stop, nothing more to substitute, therefore take the value next 17. That is 7. Subtract it with the totient.
60-7=d
Then therefore the value of d= 53.
I just want to augment the Sidudozo's answer and clarify some important points.
First of all, what should we pass to Extended Euclidean Algorthim to compute d ?
Remember that ed mod φ(n) = 1 and cgd(e, φ(n)) = 1.
Knowing that the Extended Euclidean Algorthim is based on the formula cgd(a,b) = as + bt, hence cgd(e, φ(n)) = es + φ(n)t = 1, where d should be equal to s + φ(n) in order to satisfy the
ed mod φ(n) = 1 condition.
So, given the e=17 and φ(n)=60 (borrowed from the Sidudozo's answer), we substitute the corresponding values in the formula mentioned above:
cgd(e, φ(n)) = es + φ(n)t = 1 ⇔ 17s + 60t = 1.
At the end of the Sidudozo's answer we obtain s = -7. Thus d = s + φ(n) ⇔ d = -7 + 60 ⇒ d = 53.
Let's verify the results. The condition was ed mod φ(n) = 1.
Look 17 * 53 mod 60 = 1. Correct!
The approved answer by Thilo is incorrect as it uses Euler's totient function instead of Carmichael's totient function to find d. While the original method of RSA key generation uses Euler's function, d is typically derived using Carmichael's function instead for reasons I won't get into. The math needed to find the private exponent d given p q and e without any fancy notation would be as follows:
d = e^-1*mod(((p-1)/GCD(p-1,q-1))(q-1))
Why is this? Because d is defined in the relationship
de = 1*mod(λ(n))
Where λ(n) is Carmichael's function which is
λ(n)=lcm(p-1,q-1)
Which can be expanded to
λ(n)=((p-1)/GCD(p-1,q-1))(q-1)
So inserting this into the original expression that defines d we get
de = 1*mod(((p-1)/GCD(p-1,q-1))(q-1))
And just rearrange that to the final formula
d = e^-1*mod(((p-1)/GCD(p-1,q-1))(q-1))
More related information can be found here.
Here's the code for it, in python:
def inverse(a, n):
t, newt = 0, 1
r, newr = n, a
while newr:
quotient = r // newr # floor division
t, newt = newt, t - quotient * newt
r, newr = newr, r - quotient * newr
if r > 1:
return None # there's no solution
if t < 0:
t = t + n
return t
inverse(17, 60) # returns 53
adapted from pseudocode found in wiki: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode
Simply use this formula,
d = (1+K(phi))/e. (Very useful when e and phi are small numbers)
Lets say, e = 3 and phi = 40
we assume K = 0, 1, 2... until your d value is not a decimal
assume K = 0, then
d = (1+0(40))/3 = 0. (if it is a decimal increase the K value, don't bother finding the exact value of the decimal)
assume K = 2, then
d = (1+2(40)/3) = 81/3 = 27
d = 27.
Assuming K will become exponentially easy with practice.
Taken the values p=7, q=11 and e=17.
then the value of n=p*q=77 and f(n)=(p-1)(q-1)=60.
Therefore, our public key pair is,(e,n)=(7,77)
Now for calvulating the value of d we have the constraint,
e*d == 1 mod (f(n)), [here "==" represents the **congruent symbol**].
17*d == 1 mod 60
(17*53)*d == 53 mod 60, [7*53=901, which gives modulus value 1]
1*d == 53 mod 60
hence,this gives the value of d=53.
Therefore our private key pair will be, (d,n)=(53,77).
Hope this help. Thank you!
I have the following pseudocode:
sum<-0
inc<-0
for i from 1-n
for j from 1 to i
sum<-sum+inc
inc<-inc+1
I am asked to find a closed formula. The hint is to use common summations. No matter how I look at it I cannot write this code in summation form. Can someone give me an idea of what the summations would look like or even a recursive formula?
Assuming the for i from 1-n means:
for i from 1 to n
A closed formula for that can be obtained through some numerical analysis. Let's examine the number of times through the loop for a couple of values of n (5 and 6).
The outer loop is always n times and the inner loop is whatever i is for each iteration, so for values of n, here are the iteration counts:
n count
= ===========================================
1 (1) = 1
2 (1),(12) = 3
3 (1),(12),(123) = 6
4 (1),(12),(123),(1234) = 10
5 (1),(12),(123),(1234),(12345) = 15
6 (1),(12),(123),(1234),(12345),(123456) = 21
The closed formula for these is best illustrated as follows:
n = 5: 5 + 4 + 3 + 2 + 1
| | | | |
| | V | |
| | 3 | | Formula is: (n+1)*((n-1)/2) + ((n+1)/2)
| +-> 6 <-+ | [outer pair sets] + [inner value]
+-----> 6 <-----+
--
15
This is a formula for all odd values of n. For even values, a similar method can be used:
n = 6: 6 + 5 + 4 + 3 + 2 + 1
| | | | | |
| | +-> 7 <-+ | | Formula is: (n+1)*(n/2)
| +-----> 7 <-----+ | [outer pair sets]
+---------> 7 <---------+
--
21
This tells you the number of iterations of the nested loop for each value of n (we'll call this x).
The calculation of the final value of sum is very similar. On the first iteration you add zero. On the second iteration, you add one. On the third iteration, you add two. That's pretty much exactly the same thing you had to do to figure out the number of iterations, only now it's based on x rather than n and it's 0+1+2+... rather than 1+2+3+..., meaning we can use exactly the same formula just by applying it to x-1 rather than x.
So we can use:
if n is odd:
x <- (n+1) * ((n-1)/2) + ((n+1)/2)
else:
x <- (n+1) * (n/2)
x <- x - 1
if x is odd:
sum <- (x+1) * ((x-1)/2) + ((x+1)/2)
else:
sum <- (x+1) * (x/2)
Checking this against the algorithm for the first few values on n:
n algorithm formula
- --------- -------
0 0 0
1 0 0
2 3 3
3 15 15
4 45 45
5 105 105
So, a perfect match, at least withing the sample space chosen. You could actually go further and turn that into a single formula based on n alone rather than working out an intermediate value, but I'll leave that as an exercise for the reader.
Hint: A C formula which works for both odd and even numbers is:
x <- ((n+1) * ((n-(n%2))/2)) + ((n%2) * ((n+1)/2))
(though still not tested for negative values of n - you should put a check for that before you use the formulaic version).
Innermost loop (let's just call i a fixed number):
inc is incremented i times.
sum has inc added to it i times. (i*(i-1)/2, right?)
If we assume that inc and sum start art value 0, then that's valid. If we assume that they start at some different value, let's call them k and l, then we know that inc will end up at value k+i. We know that sum will end up at l+k*i + i*(i-1)/2.
Now, i itself is going from 1 to n. Um... hum. Let me think about this a bit more.
According to wiki shifts can be used to calculate powers of 2:
A left arithmetic shift by n is
equivalent to multiplying by 2^n
(provided the value does not
overflow), while a right arithmetic
shift by n of a two's complement value
is equivalent to dividing by 2^n and
rounding toward negative infinity.
I was always wondering if any other bitwise operators (~,|,&,^) make any mathematical sense when applied to base-10? I understand how they work, but do results of such operations can be used to calculate anything useful in decimal world?
"yep base-10 is what I mean"
In that case, yes, they can be extended to base-10 in several ways, though they aren't nearly as useful as in binary.
One idea is that &, |, etc. are the same as doing arithmetic mod-2 to the individual binary digits. If a and b are single binary-digits, then
a & b = a * b (mod 2)
a ^ b = a + b (mod 2)
~a = 1-a (mod 2)
a | b = ~(~a & ~b) = 1 - (1-a)*(1-b) (mod 2)
The equivalents in base-10 would be (note again these are applied per-digit, not to the whole number)
a & b = a * b (mod 10)
a ^ b = a + b (mod 10)
~a = 9-a (mod 10)
a | b = ~(~a & ~b) = 9 - (9-a)*(9-b) (mod 10)
The first three are useful when designing circuits which use BCD (~a being the 9's complement), such as non-graphing calculators, though we just use * and + rather than & and ^ when writing the equations. The first is also apparently used in some old ciphers.
A fun trick to swap two integers without a temporary variable is by using bitwise XOR:
void swap(int &a, int &b) {
a = a ^ b;
b = b ^ a; //b now = a
a = a ^ b; //knocks out the original a
}
This works because XOR is a commutative so a ^ b ^ b = a.
Yes, there are other useful operations, but they tend to be oriented towards operations involving powers of 2 (for obvious reasons), e.g. test for odd/even, test for power of 2, round up/down to nearest power of 2, etc.
See Hacker's Delight by Henry S. Warren.
In every language I've used (admittedly, almost exclusively C and C-derivatives), the bitwise operators are exclusively integer operations (unless, of course, you override the operation).
While you can twiddle the bits of a decimal number (they have their own bits, after all), it's not necessarily going to get you the same result as twiddling the bits of an integer number. See Single Precision and Double Precision for descriptions of the bits in decimal numbers. See Fast Inverse Square Root for an example of advantageous usage of bit twiddling decimal numbers.
EDIT
For integral numbers, bitwise operations always make sense. The bitwise operations are designed for the integral numbers.
n << 1 == n * 2
n << 2 == n * 4
n << 3 == n * 8
n >> 1 == n / 2
n >> 2 == n / 4
n >> 3 == n / 8
n & 1 == {0, 1} // Set containing 0 and 1
n & 2 == {0, 2} // Set containing 0 and 2
n & 3 == {0, 1, 2, 3} // Set containing 0, 1, 2, and 3
n | 1 == {1, n, n+1}
n | 2 == {2, n, n+2}
n | 3 == {3, n, n+1, n+2, n+3}
And so on.
You can calculate logarithms using just bitwise operators...
Finding the exponent of n = 2**x using bitwise operations [logarithm in base 2 of n]
You can sometime substitute bitwise operations for boolean operations. For example, the following code:
if ((a < 0) && (b < 0)
{
do something
{
In C this can be replaced by:
if ((a & b) < 0)
{
do something
{
This works because one bit in an integer is used as the sign bit (1 indicates negative). The and operation (a & b) will be a meaningless number, but its sign will be the bitwise and of the signs of the numbers and hence checking the sign of the result will work.
This may or may not benefit performance. Doing two boolean tests/branches will be worse on a number of architectures and compilers. Modern x86 compilers can probably generate a single branch using a some of the newer instruction even with the normal syntax.
As always, if it does result in a performance increase... Comment the code - i.e. put the "normal" way of doing it in a comment and say it's equivalent but faster.
Likewise, ~ | and ^ can be used in a similar way it all the conditions are (x<0).
For comparison conditions you can generally use subtraction:
if ((a < b) | (b < c))
{
}
becomes:
if (((a-b) | (b-c)) < 0)
{
}
because a-b will be negative only if a is less than b. There can be issues with this one if you get within a factor of 2 of max int - i.e. arithmetic overflow, so be careful.
These are valid optimizations in some cases, but otherwise quite useless. And to get really ugly, floating point numbers also have sign bits... ;-)
EXAMPLE:
As an example, lets say you want to take action depending on the order of a,b,c. You can do some nested if/else constructs, or you can do this:
x = ((a < b) << 2) | ((b < c) << 1) | (c < a);
switch (x):
I have used this in code with up to 9 conditions and also using the subtractions mentioned above with extra logic to isolate the sign bits instead of less-than. It's faster than the branching equivalent. However, you no longer need to do subtraction and sign bit extraction because the standard was updated long ago to specify true as 1, and with conditional moves and such, the actual less-than can be quite efficient these days.
I'm trying to figure out how to implement RSA crypto from scratch (just for the intellectual exercise), and i'm stuck on this point:
For encryption, c = me mod n
Now, e is normally 65537. m and n are 1024-bit integers (eg 128-byte arrays). This is obviously too big for standard methods. How would you implement this?
I've been reading a bit about exponentiation here but it just isn't clicking for me:
Wikipedia-Exponentiation by squaring
This Chapter (see section 14.85)
Thanks.
edit: Also found this - is this more what i should be looking at? Wikipedia- Modular Exponentiation
Exponentiation by squaring:
Let's take an example. You want to find 1723. Note that 23 is 10111 in binary. Let's try to build it up from left to right.
// a exponent in binary
a = 17 //17^1 1
a = a * a //17^2 10
a = a * a //17^4 100
a = a * 17 //17^5 101
a = a * a //17^10 1010
a = a * 17 //17^11 1011
a = a * a //17^22 10110
a = a * 17 //17^23 10111
When you square, you double the exponent (shift left by 1 bit). When you multiply by m, you add 1 to the exponent.
If you want to reduce modulo n, you can do it after each multiplication (rather than leaving it to the end, which would make the numbers get very large).
65537 is 10000000000000001 in binary which makes all of this pretty easy. It's basically
a = m
repeat 16 times:
a = a * a
a = a mod n
a = a * m
a = a mod n
where of course a, n and m are "big integers". a needs to be at least 2048 bits as it can get as large as (n-1)2.
For an efficient algorithm you need to combine the exponentiation by squaring with repeated application of mod after each step.
For odd e this holds:
me mod n = m ⋅ me-1 mod n
For even e:
me mod n = (me/2 mod n)2 mod n
With m1 = m as a base case this defines a recursive way to do efficient modular exponentiation.
But even with an algorithm like this, because m and n will be very large, you will still need to use a type/library that can handle integers of such sizes.
result = 1
while e>0:
if (e & 1) != 0:
result = result * m
result = result mod n
m = m*m
m = m mod n
e = e>>1
return result
This checks bits in the exponent starting with the least significant bit. Each time we move up a bit it corresponds to doubling the power of m - hence we shift e and square m. The result only gets the power of m multiplied in if the exponent has a 1 bit in that position. All multiplications need to be reduced mod n.
As an example, consider m^13. 11 = 1101 in binary. so this is the same as m^8 * m^4 * m. Notice the powers 8,4,(not 2),1 which is the same as the bits 1101. And then recall that m^8 = (m^4)^2 and m^4 = (m^2)^2.
If g(x) = x mod 2^k is faster to calculate for your bignum library than f(x) = x mod N for N not divisible by 2, then consider using Montgomery multiplication. When used with modular exponentiation, it avoids having to calculate modulo N at each step, you just need to do the "Montgomeryization" / "un-Montgomeryization" at the beginning and end.