I learn how AES`s implementation work in Go and I do not understand how middle rounds work while encrypt block in https://github.com/golang/go/blob/master/src/crypto/aes/block.go:
// Middle rounds shuffle using tables.
// Number of rounds is set by length of expanded key.
nr := len(xk)/4 - 2 // - 2: one above, one more below
k := 4
for r := 0; r < nr; r++ {
t0 = xk[k+0] ^ te0[uint8(s0>>24)] ^ te1[uint8(s1>>16)] ^ te2[uint8(s2>>8)] ^ te3[uint8(s3)]
t1 = xk[k+1] ^ te0[uint8(s1>>24)] ^ te1[uint8(s2>>16)] ^ te2[uint8(s3>>8)] ^ te3[uint8(s0)]
t2 = xk[k+2] ^ te0[uint8(s2>>24)] ^ te1[uint8(s3>>16)] ^ te2[uint8(s0>>8)] ^ te3[uint8(s1)]
t3 = xk[k+3] ^ te0[uint8(s3>>24)] ^ te1[uint8(s0>>16)] ^ te2[uint8(s1>>8)] ^ te3[uint8(s2)]
k += 4
s0, s1, s2, s3 = t0, t1, t2, t3
}
I understand that this code do SybButes, ShiftRows, MixColumns and AddRoundKey of AES, but I do not understand how this code do it by using
"te0", "te1", "te2", "te3" arrays. It's precomputed arrays which are defined in https://github.com/golang/go/blob/master/src/crypto/aes/const.go.
May someone explain to me how these arrays was precomputed? Thank you so much for you help.
I have found an answer to my question in:
https://crypto.stackexchange.com/questions/19175/efficient-aes-use-of-t-tables
Generating AES (AES-256) Lookup Tables
https://golang.org/src/crypto/aes/aes_test.go
Related
Problem Statement:
There is a broken calculator. Only a few of the digits [0 to 9] and operators [+, -, *, /] are working.
A req no. needs to be formed using the working digits and the operators. Each press on the keyboard is called an operation.
= operator is always working and is used when the req no. is formed using operators.
-1 needs to be printed in case the req no. cannot be formed using the digits and the operators provided OR exceeds the max no. of operations allowed.
At no point in time during the calculation of the result, the no. should become negative or exceed 999 [0 <= calcno <= 999]
Input:
1st line contains 3 space separated nos: no. of working digits, no. of working operators, max. no of operations allowed.
2nd line contains space separated working digits.
3rd line contains space separated working operators [1 represents +, 2 represents -, 3 represents *, 4 represents /].
4th line contains the req. no to be formed.
Output:
Find the minimum required operations to form the req no.
Example:
Input 1:
2 1 8
2 5
3
50
Possible ways:
Case 1: 2*5*5 = -> 6 operations
Case 2: 2*25 = -> 4 operations
4 is the req Answer
Input 2:
3 4 8
5 4 2
3 2 4 1
42
Possible ways:
Case 1: 42 -> 2 operations (direct key in)
Case 2: 5*4*2+2 = -> 8 operations
..........some other ways
2 is the req Answer
I am not getting a proper approach to this problem.
Can someone suggest some ways to approach the problem.
Giving some more context what vish4071 said in the comments.
Set up a graph in the following way:
Starting the graph with a root, and than the new node are the number you're aloud to use (for the example this is 2 and 5). And build up the graph level by level.
Make each level in the following way, a new node will consist either of adding number or a operator which you're aloud to use. After each operator there cannot be another operator.
If the node has a higher value than the Target value, than kill the node (target as end note), this only works for this example (if the operators are * and +). If you would be able to use the - and / operator this is not vallid.
Do this till you find the required value, and the level (+1, due to the = operation) is you're answer.
And example of the graph is given below
for your first example:
D=0 D=1
5
/
Root /
\
\2
D=1 D=2 d=3 d=4
--2
/
/
(*)___5 --> reaches answer but at level 6
/
/ (*)___2 --> complete
/ / \ 5
/ /
2 /____25_252 --> end node
\ \
\ \
\
\ 225 --> end node
\ /
22__222 --> end node
\
(*)
This is slightly better than brute forcing, maybe there is a more optimal way.
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int n,m,o;
cin>>n>>m>>o;
int arr[n];
queue<pair<int,int>> q;
for(int i=0;i<n;i++)
{
cin>>arr[i];
q.push(make_pair(arr[i],1));
}
int op[m];
for(int i=0;i<m;i++) cin>>op[i];
unordered_map<int,int> mp;
for(int i=0;i<m;i++) mp[op[i]]=1;
int target;
cin>>target;
int ans=INT_MAX;
while(!q.empty())
{
int num=q.front().first;
int count=q.front().second;
if(num==target) ans=min(ans,count);
q.pop();
for(int i=0;i<=4;i++)
{
for(int j=0;j<n;j++)
{
if(i==0 and count+1<=o)
{
q.push(make_pair(num*10+arr[j],count+1));
}
else
{
if(i==1 and mp.find(i)!=mp.end() and count+3<=o)
{
q.push(make_pair(num+arr[j],count+3));
}
if(i==2 and mp.find(i)!=mp.end() and count+3<=o)
{
q.push(make_pair(abs(num-arr[j]),count+3));
}
if(i==3 and mp.find(i)!=mp.end() and count+3<=o)
{
q.push(make_pair(num*arr[j],count+3));
}
if(i==4 and mp.find(i)!=mp.end() and count+3<=o)
{
q.push(make_pair(num/arr[j],count+3));
}
}
}
}
}
if(ans==INT_MAX) cout<<"-1"<<endl;
else cout<<ans<<endl;
return 0;
}
I have been tried to do the Morris Pratt table and the code is basically this one in C:
void preMp(char *x, int m, int mpNext[]) {
int i, j;
i = 0;
j = mpNext[0] = -1;
while (i < m) {
while (j > -1 && x[i] != x[j])
j = mpNext[j];
mpNext[++i] = ++j;
}
}
and here is where i get so far in Fortran
program MP_ALGORITHM
implicit none
integer, parameter :: m=4
character(LEN=m) :: x='abac'
integer, dimension(4) :: T
integer :: i, j
i=0
T(1)=-1
j=-1
do while(i < m)
do while((j > -1) .AND. (x(i+1:i+1) /= (x(j+i+1:j+i+1))))
j=T(j)
end do
i=i+1
j=j+1
T(i)=j
end do
print *, T(1:)
end program MP_ALGORITHM
and the problem is i think i am having the wrong output.
for x=abac it should be (?):
a b a c
-1 0 1 0
and my code is returning 0 1 1 1
so, what i've done wrong?
The problem here is that C indices start from zero, but Fortran indices start from one. You can try to adjust the index for every array acces by one, but this will get unwieldy.
The Morris-Pratt table itself is an array of indices, so it should look different in C and Fortran: The Fortran array should have one-based indices and it should use zero as invalid index.
Together with the error that chw21 pointed out, your function might look like this:
subroutine kmp_table(x, t)
implicit none
character(*), intent(in) :: x
integer, dimension(:), intent(out) :: t
integer m
integer :: i, j
m = len(x)
i = 1
t(1) = 0
j = 0
do while (i < m)
do while(j > 0 .and. x(i:i) /= x(j:j))
j = t(j)
end do
i = i + 1
j = j + 1
t(i) = j
end do
end subroutine
You can then use it in the Morris-Pratt algorithm as taken straight from the Wikipedia page with adjustment for Fortran indices:
function kmp_index(S, W) result(res)
implicit none
integer :: res
character(*), intent(in) :: S ! text to search
character(*), intent(in) :: W ! word to find
integer :: m ! zero-based offset in S
integer :: i ! one-based offset in W and T
integer, dimension(len(W)) :: T ! KMP table
call kmp_table(W, T)
i = 1
m = 0
do while (m + i <= len(S))
if (W(i:i) == S(m + i:m + i)) then
if (i == len(W)) then
res = m + 1
return
end if
i = i + 1
else
if (T(i) > 0) then
m = m + i - T(i)
i = T(i)
else
i = 1
m = m + 1
end if
end if
end do
res = 0
end function
(The index m is zero-based here, because t is only ever used in conjunction with i in S(m + i:m + i). Adding two one-based indices will yield an offset of one, whereas keeping m zero-based makes this a neutral addition. m is a local variable that isn't exposed to code from the outside.)
Alternatively, you could make your Fortran arrays zero-based by specifying a lower bound of zero for your string and array. That will clash with the useful character(*) notation, though, which always uses one-based indexing. In my opinion, it is better to think about the whole algorithm in the typical one-based indexing scheme of Fortran.
this site isn't really a debugging site. Normally I would suggest you have a look at how to debug code. It didn't take me very long to go through your code with a pen and paper and verify that that is indeed the table it produces.
Still, here are a few pointers:
The C code compares x[i] and x[j], but you compare x[i] and x[i+j] in your Fortran code, more or less.
Integer arrays usually also start at index 1 in Fortran. So just like adding one to the index in the x String, you also need to add 1 every time you access T anywhere.
I need to calculate the LZ-complexity of a binary string. The LZ-complexity is the number of differencet substrings encountered as the stream is viewed from begining to the end. As an example:
s = 1001111011000010
Marking in the different substrings the sequence complexity c(s) = 6:
s = 1 / 0 / 01 / 1110 / 1100 / 0010 /
can someone guide me to find a simple solution for that? I am sure there should be some very straight-forward implementations for this well-known problem, but I have difficulty finding them. Can it be done simply done with constructing a suffix tree or something similar. If yes, exactly how? and what should I do?
anyone knows of any c/c++ source code to accomplish the task?
thanks in advance.
to clarify the construction of the tree suggested in the answers. Does the tree looks like this?
o
/ \
o o
/ \ / \
o o o o
/ /
o o
Below is a quick example of how to compute LZ-Complexity using a tree. For convenience - mine; not yours - this code implements a fixed-sized pre-allocated tree, and is a prime example of why void* pointers are ugly to use and difficult to maintain. Hand this code in as is, and your lecturer is likely to shoot you in the face :)
#include <stdlib.h>
#include <stdio.h>
int LZComplexity(char *p_binarySequence, int p_maxTreeNodes)
{
void **patternTree;
void **currentNode;
void **nextFreeNode;
int nodeCount;
int sequenceIndex;
int currentDigit;
nodeCount = 0;
patternTree = malloc(sizeof(void*) * (p_maxTreeNodes << 1));
currentNode = patternTree;
nextFreeNode = patternTree + (sizeof(void*) << 1);
currentNode[0] = NULL;
currentNode[1] = NULL;
sequenceIndex = 0;
while (p_binarySequence[sequenceIndex])
{
currentDigit = p_binarySequence[sequenceIndex] - 48;
if (NULL == currentNode[currentDigit])
{
currentNode[currentDigit] = nextFreeNode;
nextFreeNode[0] = NULL;
nextFreeNode[1] = NULL;
nextFreeNode += (sizeof(void*) << 1);
currentNode = patternTree;
nodeCount++;
}
else
{
currentNode = currentNode[currentDigit];
}
sequenceIndex++;
}
free(patternTree);
return nodeCount;
}
int main(int argc, char *argv[])
{
printf("%u\n", LZComplexity("10100101001011101011", 1000));
return 0;
}
1 0 01 11 10 110 00 010
Complexity of sequence is 8 because the partitions are 8 not 6 - 1/0/01/11/10/110/00/010
#Arash and #Sanchit Gupta: You might've got confused between LZ76 complexity and LZ78 complexity. The one Arash is refering to is LZ76 complexity and the other one is LZ78 complexity. You can refer to section-3 of the paper "Estimating the Entropy Rate of Spike Trains via Lempel-Ziv Complexity".
Guillermo Valle has an implementation that produces the right answers (unlike e.g. the current Wikipedia code).
For instance,
Complexity of 0001 is 2: 0 001
Complexity of 010 is 3: 0 1 0
Create a binary tree where left is 0 and right is 1. For each bit, try to find the sequence in the tree. If it's there, concatenate the next bit, rinse, repeat. If it's not there, add it to the tree and continue. LZ Complexity is the total number of paths in the tree (not just # leaf nodes).
By the way, is this homework?
This may be relevant for you. It is parallel implementation
of an algorithm LZMP that computes the LZ-complexity
in CUDA and runs on nVidia GPU.
http://www.ariel.ac.il/sites/ratsaby/Code/LZMP.zip
This should do the trick in Python (from: Kaspar, F. Schuster, H. Easily calculable measure for the complexity of spatiotemporal patterns. Physical Review A, vol 36, n. 2, p 842.)
#!/usr/bin/python
def lz_complexity(s):
i, k, l = 0, 1, 1
k_max = 1
n = len(s) - 1
c = 1
while True:
if s[i + k - 1] == s[l + k - 1]:
k = k + 1
if l + k >= n - 1:
c = c + 1
break
else:
if k > k_max:
k_max = k
i = i + 1
if i == l:
c = c + 1
l = l + k_max
if l + 1 > n:
break
else:
i = 0
k = 1
k_max = 1
else:
k = 1
return c
def main():
lz = lz_complexity('1001111011000010')
assert lz == 6
print lz
if __name__ == '__main__':
main()
Is there a one line expression (possibly boolean) to get the nearest 2^n number for a given integer?
Example: 5,6,7 must be 8.
Round up to the next higher power of two: see bit-twiddling hacks.
In C:
unsigned int v; // compute the next highest power of 2 of 32-bit v
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
I think you mean next nearest 2^n number. You can do a log on the mode 2 and then determine next integer value out of it.
For java, it can be done like:
Math.ceil(Math.log(x)/Math.log(2))
Since the title of the question is "Round to the nearest power of two", I thought it would be useful to include a solution to that problem as well.
int nearestPowerOfTwo(int n)
{
int v = n;
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++; // next power of 2
int x = v >> 1; // previous power of 2
return (v - n) > (n - x) ? x : v;
}
It basically finds both the previous and the next power of two and then returns the nearest one.
Your requirements are a little confused, the nearest power of 2 to 5 is 4. If what you want is the next power of 2 up from the number, then the following Mathematica expression does what you want:
2^Ceiling[Log[2, 5]] => 8
From that it should be straightforward to figure out a one-liner in most programming languages.
For next power of two up from a given integer x
2^(int(log(x-1,2))+1)
or alternatively (if you do not have a log function accepting a base argument
2^(int(log(x-1)/log(2))+1)
Note that this does not work for x < 2
This can be done by right shifting on the input number until it becomes 0 and keeping the count of shifts. This will give the position of the most significant 1 bit. Getting 2 to the power of this number will give us the next nearest power of 2.
public int NextPowerOf2(int number) {
int pos = 0;
while (number > 0) {
pos++;
number = number >> 1;
}
return (int) Math.pow(2, pos);
}
For rounding up to the nearest power of 2 in Java, you can use this. Probably faster for longs than the bit-twiddling stuff mentioned in other answers.
static long roundUpToPowerOfTwo(long v) {
long i = Long.highestOneBit(v);
return v > i ? i << 1 : i;
}
Round n to the next power of 2 in one line in Python:
next_power_2 = 2 ** (n - 1).bit_length()
Modified for VBA. NextPowerOf2_1 doesn't seem to work. So I used loop method. Needed a shift right bitwise operator though.
Sub test()
NextPowerOf2_1(31)
NextPowerOf2_2(31)
NextPowerOf2_1(32)
NextPowerOf2_2(32)
End Sub
Sub NextPowerOf2_1(ByVal number As Long) ' Does not work
Debug.Print 2 ^ (Int(Math.Log(number - 1) / Math.Log(2)) + 1)
End Sub
Sub NextPowerOf2_2(ByVal number As Long)
Dim pos As Integer
pos = 0
While (number > 0)
pos = pos + 1
number = shr(number, 1)
Wend
Debug.Print 2 ^ pos
End Sub
Function shr(ByVal Value As Long, ByVal Shift As Byte) As Long
Dim i As Byte
shr = Value
If Shift > 0 Then
shr = Int(shr / (2 ^ Shift))
End If
End Function
Here is a basic version for Go
// Calculates the next highest power of 2.
// For example: n = 15, the next highest power of 2 would be 16
func NearestPowerOf2(n int) int {
v := n
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
return v
}
The function a = 2 ^ b can quickly be calculated for any b by doing a = 1 << b.
What about the other way round, getting the value of b for any given a? It should be relatively fast, so logs are out of the question. Anything that's not O(1) is also bad.
I'd be happy with can't be done too if its simply not possible to do without logs or a search type thing.
Build a look-up table. For 32-bit integers, there are only 32 entries so it is O(1).
Most architectures also have an instruction to find the position of the most significant bit of a number a, which is the value b. (gcc provides the __builtin_clz function for this.)
For a BigInt, it can be computed in O(log a) by repeatedly dividing by 2.
int b = -1;
while (a != 0) {
a >>= 1;
++ b;
}
For this sort of thing I usually refer to this page with bit hacks:
Bit Twiddling Hacks
For example:
Find the log base 2 of an integer with a lookup table:
static const char LogTable256[256] =
{
#define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
-1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6),
LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7)
};
unsigned int v; // 32-bit word to find the log of
unsigned r; // r will be lg(v)
register unsigned int t, tt; // temporaries
if (tt = v >> 16)
{
r = (t = tt >> 8) ? 24 + LogTable256[t] : 16 + LogTable256[tt];
}
else
{
r = (t = v >> 8) ? 8 + LogTable256[t] : LogTable256[v];
}
There are also a couple of O(log(n)) algorithms given on that page.
Some architectures have a "count leading zeros" instruction. For example, on ARM:
MOV R0,#0x80 # load R0 with (binary) 10000000
CLZ R1,R0 # R1 = number of leading zeros in R0, i.e. 7
This is O(1).
Or you can write:
while ((a >>= 1) > 0) b++;
This is O(1). One could imagine this to be expanded to:
b = (((a >> 1) > 0) ? 1 : 0) + (((a >> 2) > 0) ? 1 : 0) + ... + (((a >> 31) > 0) ? 1 : 0);
With a complier optimization, that once (a >> x) > 0) returns false, rest won't be calculated. Also comparing with 0 is faster then any other comparison. Also:
, where k is maximum of 32 and g is 1.
Reference: Big O notation
But in case you where using BigInteger, then my code example would look like:
int b = 0;
String numberS = "306180206916083902309240650087602475282639486413"
+ "866622577088471913520022894784390350900738050555138105"
+ "234536857820245071373614031482942161565170086143298589"
+ "738273508330367307539078392896587187265470464";
BigInteger a = new BigInteger(numberS);
while ((a = a.shiftRight(1)).compareTo(BigInteger.ZERO) > 0) b++;
System.out.println("b is: " + b);
If a is a double rather than an int then it will be represented as mantissa and exponent. The exponent is the part you are looking for, as this is the logarithm of the number.
If you can hack the binary representation then you can get the exponent out. Look up the IEEE standard to see where and how the exponent is stored.
For an integral value, if some method of getting the most significant bit position is not available then you can binary-search the bits for the upper-most 1 which is therefore O(log numbits). Doing this may well actually perform faster than converting to a double first.
In Java you can use Integer.numberOfLeadingZeros to compute the binary logarithm. It returns the number of leading zeros in the binary representation, so
floor(log2(x)) = 31 - numberOfLeadingZeros(x)
ceil(log2(x)) = 32 - numberOfLeadingZeros(x - 1)
It can't be done without testing the high bit, but most modern FPUs support log2 so all is not lost.