how to prove that the hash function h(x) = x² mod 4 yields only to 0 and 1 - hash

How can I prove that the hash function h(x) = x² mod 4 yields only to {0, 1}, with x as an element of the natural numbers?

Let's first cover the even numbers, 2n (where n is a natural number):
(2n)2
= (2n)(2n)
= (2)(n)(2)(n)
= (2)(2)(n)(n)
= 4n2
= 4(n2)
That's an exact multiple of four so the remainder when dividing by four will always be zero.
Now let's cover the odd numbers, 2n + 1:
(2n + 1)2
= (2n + 1)(2n + 1)
= (2n)(2n) + (2n)(1) + (1)(2n) + (1)(1)
= 4n2 + 2n + 2n + 1
= 4n2 + 4n + 1
= 4(n2 + n) + 1
That's exactly one more than a multiple of four hence the remainder when dividing by four will always be one.
Now, let's look at any natural numbers that are neither even nor odd.
Wait a minute, there aren't any. I guess that means we're done :-)
And, before anyone points out that some languages may give a negative remainder when the arguments are negative, that doesn't actually apply here since the square of a natural number can never be negative.

Related

Why is the following code correct for computing the hash of a string?

I am currently reading about the Rabin Karp algorithm and as part of that I need to understand string polynomial hashing. From what I understand, the hash of a string is given by the following formula:
hash = ( char_0_val * p^0 + char_1_val * p^1 + ... + char_n_val ^ p^n ) mod m
Where:
char_i_val: is the integer value of the character plus 1 given by string[i]-'a' + 1
p is a prime number larger than the character set
m is a large prime number
The website cp-algorithms has the following entry on the subject. They say that the code to write the above is as follows:
long long compute_hash(string const& s) {
const int p = 31;
const int m = 1e9 + 9;
long long hash_value = 0;
long long p_pow = 1;
for (char c : s) {
hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
p_pow = (p_pow * p) % m;
}
return hash_value;
}
I understand what the program is trying to do but I do not understand why it is correct.
My question
I am having trouble understanding why the above code is correct. It has been a long time since I have done any modular math. After searching online I see that we have the following formulas for modular addition and modular multiplication:
a+b (mod m) = (a%m + b%m)%m
a*b (mod m) = (a%m * b%m)%m
Based on the above shouldn't the code be as follows?
long long compute_hash(string const& s) {
const int p = 31;
const int m = 1e9 + 9;
long long hash_value = 0;
long long p_pow = 1;
for (char c : s) {
int char_value = (c - 'a' + 1);
hash_value = (hash_value%m + ((char_value%m * p_pow%m)%m)%m ) % m;
p_pow = (p_pow%m * p%m) % m;
}
return hash_value;
}
What am I missing? Ideally I am seeking a breakdown of the code and an explanation of why the first version is correct.
Mathematically, there is no reason to reduce intermediate results modulo m.
Operationally, there are a couple of very closely related reasons to do it:
To keep numbers small enough that they can be represented efficiently.
To keep numbers small enough that operations on them do not overflow.
So let's look at some quantities and see if they need to be reduced.
p was defined as some value less than m, so p % m == p.
p_pow and hash_value have already been reduced modulo m when they were computed, reducing them modulo m again would do nothing.
char_value is at most 26, which is already less than m.
char_value * p_pow is at most 26 * (m - 1). That can be, and often will be, more than m. So reducing it modulo m would do something. But it can still be delayed, because the next step is still "safe" (no overflow)
char_value * p_pow + hash_value is still at most 27 * (m - 1) which is still much less than 263-1 (the maximum value for a long long, see below why I assume that a long long is 64-bit), so there is no problem yet. It's fine to reduce modulo m after the addition.
As a bonus, the loop could actually do (263-1) / (27 * (m - 1)) iterations before it needs to reduce hash_value modulo m. That's over 341 million iterations! For most practical purposes you could therefore remove the first % m and return hash_value % m; instead.
I used 263-1 in this calculation because p_pow = (p_pow * p) % m requires long long to be a 64-bit type (or, hypothetically, an exotic size of 36 bits or higher). If it was a 32-bit type (which is technically allowed, but rare nowadays) then the multiplication could overflow, because p_pow can be approximately a billion and a 32-bit type cannot hold 31 billion.
BTW note that this hash function is specifically for strings that only contain lower-case letters and nothing else. Other characters could result in a negative value for char_value which is bad news because the remainder operator % in C++ works in a way such that for negative numbers it is not the "modulo operator" (misnomer, and the C++ specification does not call it that). A very similar function can be written that can take any string as input, and that would change the analysis above a little bit, but not qualitatively.

Formula to obtain amount to add to Starting Value so the added amount will = 5% of New Total

Is there a formula that will work in T-SQL that can obtain the following?
Solve for x where adding x to starting value, will equal 105% of starting value.
Example
Starting value of 380.
Add x to 380 so that x is 5% of total (380 + x)
In this case, x is an even 20.
This is not 5% of the Starting value, which, would be simple. I'm looking for x to equal 5% of the new value after it's been added to the starting value.
Thank you!
I'm looking for x to equal 5% of the new value after it's been added to the starting value.
Let's do some 9th grade algebra :) I'll even show my work.
If S is the starting value, we have this equation:
x = 0.05 * (S + x)
Now solve for x:
x = 0.05S + 0.05x // distribute the constant
0.95x = 0.05S // subtract the smaller x term from both sides
x = (0.05 / 0.95) * S // divide the 0.95 from both sides
x = S / 19 // multiply the right side by 1 (20/20) to simplify
So we see you can divide the starting value by 19 to get the desired x value.
And an alternative way to solve the equation, because I think this kind of thing is fun:
x = (1/20) * (S + x) // convert the decimal to a fraction
x = (S + x) / 20 // reduce/simplify the fraction multiplication
20x = S + x // multiply both sides by 20, to remove division
19x = S // subtract the smaller x term from both sides
// (hey, we solved for S along the way)
x = S / 19 // Divide both sides by 19
It's always nice when two approaches give the same solution :). This was more steps, but the steps were simpler.

Find all numbers which are equal to the sum of the factorial of their digits

How can Find all numbers (e.g. 145= 1! + 4! + 5! = 1 + 24 + 120 = 145.)
which are equal to the sum of the factorial of their digits, by MATLAB?
I want to chop off digits, add the factorial of the digits together and compare it with the original number. If factorial summation be equal to original number, this numbers is on of the solution and must be keep. I can't code my idea, How can I code it? Is this true?
Thanks
The main reason that I post this answer is that I can't leave the use of eval in the previous answer without a decent alternative
Here is a small function to check this for any given (integer) n:
isFact = #(n) n==sum(factorial(int2str(n)-'0'));
Explanation:
int2str(n)-'0': "chop off digits"
sum(factorial(...)): "add the factorial of the digits together"
n==...: "compare it with the original number"
You can now plug it in a loop to find all the numbers between 1 to maxInt:
maxInt = 100000; % just for the example
solution = false(1,maxInt); % preallocating memory
for k = 1:maxInt
solution(k) = isFact(k);
end
find(solution) % find all the TRUE indices
The result:
ans =
1 2 145 40585
The loop above was written to be simple. If you look for further efficiency and flexibility (like not checking all the numbers between 1 to maxInt and checking array in any shape), you can change it to:
% generating a set of random numbers with no repetitions:
Vec2Check = unique(randi(1000,1,1000)); % you can change that to any array
for k = 1:numel(Vec2Check)
if isFact(Vec2Check(k))
Vec2Check(k) = Vec2Check(k)+0.1;
end
end
solution = Vec2Check(Vec2Check>round(Vec2Check))-0.1
The addition of 0.1 serves as a 'flag' that marks the numbers that isFact returns true for them. We then extract them by comparing the vector to it's rounded vertsion.
You can even go with a one-line solution:
solution = nonzeros(arrayfun(#(n) n.*(n==sum(factorial(int2str(n)-'0'))),Vec2Check))
The following snippet finds the numbers up to 1000 satisfying this condition.
numbers = [];
for i=1:1000
number_char = int2str(i);
sum = 0;
for j=1:length(number_char)
sum = sum+ factorial(eval(number_char(j)));
end
if (sum == i)
numbers(end+1) = i;
end
end
disp(numbers)
This should yield:
1 2 145
Note that if (log10(n)+1)*9! is less than n, then there is no number satisfying the condition larger than n.

How to Increment a 3 digit Number(User Input) by 1 in Brainfuck?

How to Increment a 3 digit Number by 1 in Brainfuck?
For Example. Getting a User input of 699 this code should output 700.
This is something i Tried but its not working .
,>,>,+
<<.>.>.
The reason it doesn't work is because you don't have a 3 digit number in memory. You have three ASCII values from 48-57 (characters 0-9). I will explain how to do what you need to, but won't provider the actual BF code for multiplication etc, you can find those elsewhere.
Let's call the characters X, Y and Z
First of all we need to convert them to a number between 0 and 9. Assuming that the user enters digits only, we can do this by subtracting 48 (ASCII character 0) from the ASCII value.
Ok so now we have three numbers from 0-9 as follows:
A = X - 48
B = Y - 48
C = Z - 48
Problem is they're still three separate digits and not one number. What's the actual number? In this case the number can be built in the following way:
N = 100A + 10B + C
So, you need to multiply A by 100, B by 10, C by 1, and then adding them all together. Could be done as follows:
N = A
N = (N * 10) + B
N = (N * 10) + C
After you've done that, you have an actual number in one cell, and you can increment it by doing N = N + 1 which in BF is a single +
Now this would work for numbers up to 255, which is the largest number that a BF cell can hold. You want to work with larger numbers? It gets more complicated, because now you have to split that number up into two or more cells, propagating the carries yourself etc. I won't go into that here because that gets much more complex (though there are algorithms you can find online to help as well) and I think this is enough to get you started.
EDIT: I realized that your code is also trying to print the incremented value. This requires more work, because the . command outputs the value of that cell as is as an ASCII character. But you need to output three digits. To do that you'd need to reverse the process above to split the number into three digits as follows:
C = N % 10
N = N / 10
B = N % 10
N = N / 10
A = N
Then you need to convert them from a number 0-9 to ASCII characters again as follows:
X = A + 48
Y = B + 48
Z = C + 48
and then finally you can output characters X, Y and Z in that order which would be the human readable incremented number.

Create an increasing integer alternating sequence in MATLAB / Octave

I'm trying to find a way to create a number pattern like the one below
0,1,-2,3,-4,5....
Please note: it needs to go to 200000, but I will be splitting them up into groups of 2000.
I found a formula that looks like it would work on http://oeis.org/A181983, but when I create the formula in MATLAB / Octave, the numbers don't match up:
f_num= #(x) x / (1 + x)^2;
numval = f_num(1)
numval = 0.25000
Is there another way I should be doing this?
Method #1 - Using (-1)^x
Just use a linear increment operator to go from 0 to 200000 and multiply the sequence by (-1)^(x+1) to allow the sign of the sequence to alternate:
x = 0:200000;
y = ((-1).^(x+1)) .* x;
The addition of the +1 is important so that the even positions get a positive sign while the odd positions get a negative sign.
Method #2 - Using indexing
Alternatively, you can declare the same array from 0 to 200000, index into every even position and negate the sign:
x = 0:200000;
x(2:2:end) = -x(2:2:end);
Method #3 - Using trigonometry and integers
One more to throw into the mix. You know that for cos(x*pi), the output is -1 when x is odd and the output is 1 when x is even. We need to flip this for your case and ultimately use this alternating sequence to multiply with the same array going from 0 to 200000, and therefore:
x = 0:200000;
y = (-cos(x*pi)).*x;
Aside
Interestingly enough, (-1)^x is also equal to exp(i*pi*x) for all values of x that are integer. We can verify this by using Euler's formula where: exp(i*pi*x) = cos(pi*x) + i*sin(pi*x). Since i*sin(pi*x) = 0 for all x belonging to an integer, we really get exp(i*pi*x) = cos(pi*x). Substituting even numbers of x will give us 1 while odd numbers of x will give us -1, and hence exp(i*pi*x) = cos(pi*x) = (-1)^x for all x belonging to integers.
Also, (-1)^(x+1) = -(-1)^x = -cos(x*pi) for all x belonging to integers and so the first method is really equal to the third method anyway!
try
f_num= #(x) x * (-1)^(x+1);