Math: What is the Equation that on increasing the integer x returns an alternate of 0 and 1? - math

What is the Equation that on increasing the integer x returns an alternate of 0 and 1
example
x = 22
result 1
x = 23
result 0
x = 24
result 1

Based on the example data, it would be modulo 2. Assuming x is an int (and C/C++/C#):
(x + 1) % 2;

In C or C++ this would be
int y = (x+1)%2;
mathematically,
y = (x+1) modulo 2

It's called modulo. You can use mod by 2 after adding one in the value.
x = 22
result = (x+1) modulo 2
In programming languages, it's often called %:
x = 22
result = (x+1) % 2 //<< result 1
x = 23
result = (x+1) % 2 //<< result 0
and so on..

Related

Expressing Natural Number by sum of Triangular numbers

Triangular numbers are numbers which is number of things when things can be arranged in triangular shape.
For Example, 1, 3, 6, 10, 15... are triangular numbers.
o o o o o o o o o o is shape of n=4 triangular number
what I have to do is A natural number N is given and I have to print
N expressed by sum of triangular numbers.
if N = 4
output should be
1 1 1 1
1 3
3 1
else if N = 6
output should be
1 1 1 1 1 1
1 1 1 3
1 1 3 1
1 3 1 1
3 1 1 1
3 3
6
I have searched few hours and couldn't find answers...
please help.
(I am not sure this might help, but I found that
If i say T(k) is Triangular number when n is k, then
T(k) = T(k-1) + T(k-3) + T(k-6) + .... + T(k-p) while (k-p) > 0
and p is triangular number )
Here's Code for k=-1(Read comments below)
#include <iostream>
#include <vector>
using namespace std;
long TriangleNumber(int index);
void PrintTriangles(int index);
vector<long> triangleNumList(450); //(450 power raised by 2 is about 200,000)
vector<long> storage(100001);
int main() {
int n, p;
for (int i = 0; i < 450; i++) {
triangleNumList[i] = i * (i + 1) / 2;
}
cin >> n >> p;
cout << TriangleNumber(n);
if (p == 1) {
//PrintTriangles();
}
return 0;
}
long TriangleNumber(int index) {
int iter = 1, out = 0;
if (index == 1 || index == 0) {
return 1;
}
else {
if (storage[index] != 0) {
return storage[index];
}
else {
while (triangleNumList[iter] <= index) {
storage[index] = ( storage[index] + TriangleNumber(index - triangleNumList[iter]) ) % 1000000;
iter++;
}
}
}
return storage[index];
}
void PrintTriangles(int index) {
// What Algorithm?
}
Here is some recursive Python 3.6 code that prints the sums of triangular numbers that total the inputted target. I prioritized simplicity of code in this version. You may want to add error-checking on the input value, counting the sums, storing the lists rather than just printing them, and wrapping the entire routine into a function. Setting up the list of triangular numbers could also be done in fewer lines of code.
Your code saved time but worsened memory usage by "memoizing" the triangular numbers (storing and reusing them rather than always calculating them when needed). You could do the same to the sum lists, if you like. It is also possible to make this more in the dynamic programming style: find the sum lists for n=1 then for n=2 etc. I'll leave all that to you.
""" Given a positive integer n, print all the ways n can be expressed as
the sum of triangular numbers.
"""
def print_sums_of_triangular_numbers(prefix, target):
"""Print sums totalling to target, each after printing the prefix."""
if target == 0:
print(*prefix)
return
for tri in triangle_num_list:
if tri > target:
return
print_sums_of_triangular_numbers(prefix + [tri], target - tri)
n = int(input('Value of n ? '))
# Set up list of triangular numbers not greater than n
triangle_num_list = []
index = 1
tri_sum = 1
while tri_sum <= n:
triangle_num_list.append(tri_sum)
index += 1
tri_sum += index
# Print the sums totalling to n
print_sums_of_triangular_numbers([], n)
Here are the printouts of two runs of this code:
Value of n ? 4
1 1 1 1
1 3
3 1
Value of n ? 6
1 1 1 1 1 1
1 1 1 3
1 1 3 1
1 3 1 1
3 1 1 1
3 3
6

Torch - Query matrix with another matrix

I have a m x n tensor (Tensor 1) and another k x 2 tensor (Tensor 2) and I wish to extract all the values of Tensor 1 using indices based on Tensor 2. For example;
Tensor1
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
[torch.DoubleTensor of size 4x5]
Tensor2
2 1
3 5
1 1
4 3
[torch.DoubleTensor of size 4x2]
And the function would yield;
6
15
1
18
The first solution that comes into mind is to simply loop through indexes and pick the correspoding values:
function get_elems_simple(tensor, indices)
local res = torch.Tensor(indices:size(1)):typeAs(tensor)
local i = 0
res:apply(
function ()
i = i + 1
return tensor[indices[i]:clone():storage()]
end)
return res
end
Here tensor[indices[i]:clone():storage()] is just a generic way to pick an element from a multi-dimensional tensor. In k-dimensional case this is exactly analogous to tensor[{indices[i][1], ... , indices[i][k]}].
This method works fine if you don't have to extract lots of values (the bottleneck is :apply method which is not able to use many optimization techniques and SIMD instructions because the function it executes is a black box). The job can be done way more efficiently: the method :index does exactly what you need... with a one-dimensional tensor. Multi-dimensional target/index tensors need to be flattened:
function flatten_indices(sp_indices, shape)
sp_indices = sp_indices - 1
local n_elem, n_dim = sp_indices:size(1), sp_indices:size(2)
local flat_ind = torch.LongTensor(n_elem):fill(1)
local mult = 1
for d = n_dim, 1, -1 do
flat_ind:add(sp_indices[{{}, d}] * mult)
mult = mult * shape[d]
end
return flat_ind
end
function get_elems_efficient(tensor, sp_indices)
local flat_indices = flatten_indices(sp_indices, tensor:size())
local flat_tensor = tensor:view(-1)
return flat_tensor:index(1, flat_indices)
end
The difference is drastic:
n = 500000
k = 100
a = torch.rand(n, k)
ind = torch.LongTensor(n, 2)
ind[{{}, 1}]:random(1, n)
ind[{{}, 2}]:random(1, k)
elems1 = get_elems_simple(a, ind) # 4.53 sec
elems2 = get_elems_efficient(a, ind) # 0.05 sec
print(torch.all(elems1:eq(elems2))) # true

Subtraction operation using only increment, loop, assign, zero

I am trying to build up subtraction, addition, division, multiplication and other operations using only following ones:
incr(x) - Once this function is called it will assign x + 1 to x
assign(x, y) - This function will assign the value of y to x (x = y)
zero(x) - This function will assign 0 to x (x = 0)
loop X { } - operations written within brackets will be executed X times
Using following rules it is straight forward to implement addition (add) like this:
ADD (x, y) {
loop X {
y = incr (y)
}
return y
}
However, I'm struggling to implement subtraction. I think that all the other needed operations could be completed using subtraction.
Any hint will be very appreciated.
Stephen Cole Kleene devised a way to perform integer subtraction using integer addition. However, it assumes that you cannot have negative integers. For example:
0 - 1 = 0
1 - 1 = 0
2 - 1 = 1
3 - 1 = 2
4 - 1 = 3
5 - 2 = 3
6 - 3 = 3
6 - 4 = 2
6 - 5 = 1
6 - 6 = 0
6 - 7 = 0
In your question, you implemented the addition operation using the increment operation.
Similarly, you can implement the subtraction operation using the decrement operation as follows:
sub(x, y) {
loop y
{ x = decr(x) }
return x
}
Now, all we need to do is implement the decrement operation.
This is where the genuis of Kleene shines:
decr(x) {
y = 0
z = 0
loop x {
y = z
z = incr(z)
}
return y
}
Here we've used all the four operations. This is how it works:
We have two base cases, y (the base case for 0) and z (the base case for 1):
y = 0 - 1 = 0
z = 1 - 1 = 0
Hence, we initialize them both to 0.
When x is 0 we run the loop 0 times (i.e. never) and then we simply return y = 0.
When x is 1 then we run the loop once, assign y = z and then simply return y = z = 0.
Notice that every time we run the loop y holds the result of the current iteration while z holds the result of the next iteration. This is the reason why we require two base cases. The decrement function is not a continuous function. It is a piecewise function:
decr(0) = 0
decr(n + 1) = n
Kleene realized this when he went to the dentist and the dentist extracted two of his teeth. He was frustrated while trying to solve this very problem and when the dentist extracted two of his teeth he realized that he required two base cases.

Calculating Total Number of Times of Loops

I'm trying to calculate the total number of times the innermost statement is executed.
count = 0;
for i = 1 to n
for j = 1 to n - i
count = count + 1
I figured that the most the loop can execute is O(n*n-i) = O(n^2). I wanted to prove this by using double summation but I'm getting lost since the I'm having trouble starting the equation since j = 1 is thrown into there.
Can someone help me explain this to me?
Thanks
For each i, the inner loop executes n - i times (n is constant). Therefore (since i ranges from 1 to n), to determine the total number of times the innermost statement is executed, we must evaluate the sum
(n - 1) + (n - 2) + (n - 3) + ... + (n - n)
By rearranging the terms (grouping all the ns that appear first), we can see that this is equal to
n*n - (1 + 2 + 3 + ... + n) = n*n - n(n+1)/2 = n*(n-1)/2 = n*n/2 - n/2
Here's a simple implementation in Python to verify this:
def f(n):
count = 0;
for i in range(1, n + 1):
for _ in range(1, n - i + 1):
count = count + 1
return count
for n in range(1,11):
print n, '\t', f(n), '\t', n*n/2 - n/2
Output:
1 0 0
2 1 1
3 3 3
4 6 6
5 10 10
6 15 15
7 21 21
8 28 28
9 36 36
10 45 45
The first column is n, the second is the number of times that inner statement is executed, and the third is n*n/2 - n/2.

What math do I need to convert numbers according to this table?

Given an X, what math is needed to find its Y, using this table?
x
y
0
1
1
0
2
6
3
5
4
4
5
3
6
2
This is a language agnostic problem. I can't just store the array, and do the lookup. The input will always be the finite set of 0 to 6. It won't be scaling later.
This:
y = (8 - x) % 7
This is how I arrived at that:
x 8-x (8-x)%7
----------------
0 8 1
1 7 0
2 6 6
3 5 5
4 4 4
5 3 3
6 2 2
int f(int x)
{
return x["I#Velcro"] & 7;
}
0.048611x^6 - 0.9625x^5 + 7.340278x^4 - 26.6875x^3 + (45 + 1/9)x^2 - 25.85x + 1
Sometimes the simple ways are best. ;)
It looks like:
y = (x * 6 + 1) % 7
I don't really like the % operator since it does division so:
y = (641921 >> (x*3)) & 7;
But then you said something about not using lookup tables so maybe this doesn't work for you :-)
Update:
Since you want to actually use this in real code and cryptic numbers are not nice, I can offer this more maintainable variant:
y = (0x2345601 >> (x*4)) & 15;
Though it seems a bunch of correct answers have already appeared, I figured I'd post this just to show another way to have worked it out (they're all basically variations on the same thing):
Well, the underlying pattern is pretty simple:
x y
0 6
1 5
2 4
3 3
4 2
5 1
6 0
y = 6 - x
Your data just happens to have the y values shifted "down" by two indices (or to have the x values shifted "up").
So you need a function to shift the x value. This should do it:
x = (x + 5) % 7;
Resulting equation:
y = 6 - ((x + 5) % 7);
Combining the ideas in Dave and Paul's answer gives the rather elegant:
y = (8 - x) % 7`
(though I see I was beaten to the punch with this)
unsigned short convertNumber(unsigned short input) {
if (input <= 1) { return !input; } //convert 0 => 1, 1 => 0
return (8-input); //convert 2 => 6 ... 6 => 2
}
Homework?
How about:
y = (x <= 1 ? 1 : 8) - x
and no, i dont/cant just store the array, and do the lookup.
Why not?
yes, the input will always be the finite set of 0 to 6. it wont be scaling later.
Just use a bunch of conditionals then.
if (input == 0) return 1;
else if (input == 1) return 0;
else if (input == 2) return 6;
...
Or find a formula if it's easy to see one, and it is here:
if (input == 0) return 1;
else if (input == 1) return 0;
else return 8 - input;
Here's a way to avoid both modulo and conditionals, going from this:
y = (8 - x) % 7
We know that x % y = x - floor(x/y)*y
So we can use y = 8 - x - floor((8 - x) / 7) * 7
What about some bit-fu ?
You can get the result using only minus, logical operators and shifts.
b = (x >> 2) | ((x >> 1) & 1)
y = ((b << 3)|(b ^ 1)) - x

Resources