Division with numerator 2^64 - math

How to to divide the constant 2^64 (i.e. ULLONG_MAX + 1) by uint64 larger than 2, without using unit128?
In other words, given x such as 2 <= x <= 2^64-1, how to obtain the quotient 2^64 / x, using just uint64?
The problem is that I cannot represent 2^64, let alone to divide it so I was hoping there is a trick which would simulate the result.

How to to divide the constant 2^64 (i.e. ULLONG_MAX + 1) by uint64 larger than 2
a/b --> (a-b)/b + 1
First subtract x from (max _value + 1), then divide by x, add 1.
// C solution:
uint64_t foo(uint64_t x) {
return (0u - x)/x + 1; // max_value + 1 is 0 and unsigned subtraction wraps around.
}
Of course division by 0 is a no-no. Code works for x >= 2, but not x == 1 as the quotient is also not representable.

Take ULLONG_MAX / denom, and add 1 if denom is a power of 2. In pseudocode:
if (denom == 0) {
throw ZeroDivisionException;
} else if (denom == 1) {
throw OverflowException;
} else {
return ULLONG_MAX / denom + (denom & (denom-1) == 0);
}
Alternatively, take ULLONG_MAX / denom for odd denom, and take 2^63 / (denom / 2) for even denom:
if (denom == 0) {
throw ZeroDivisionException;
} else if (denom == 1) {
throw OverflowException;
} else if (denom & 1) {
return ULLONG_MAX / denom;
} else {
return (1ULL << 63) / (denom >> 1);
}

Related

Why am i getting different output if I use "return"?

Why do I need to use return statement before recursively calling BubbleSort function?
without return statement : no output
void BubbleSort(int arr[], int n, int j)
{
if(n == 1)
return;
if(j == n - 1)
{
BubbleSort(arr, n - 1, 0);
}
if(arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
BubbleSort(arr, n, j + 1);
return;
}
with return statement : gives the correct output
void BubbleSort(int arr[], int n, int j)
{
if(n == 1)
return;
if(j == n - 1)
{
return BubbleSort(arr, n - 1, 0);
}
if(arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
BubbleSort(arr, n, j + 1);
return;
}
By specifying return keyword we are assure that the control of program will move to its caller.
BubbleSort(arr, n - 1, 0);
when you're executing this, without return keyword, it's calling self and the control is not returning to it's caller therefore rest of the code also executing and it does change the business which was not intended and you might getting some messy things to your result.
the following snippet might help you to understand it better:
if(j == n - 1)
{
BubbleSort(arr, n - 1, 0);
return; // returns to it caller.
}

FINDING total number of paths using backtracking

I'm trying to count total paths in a 20x20 grid(ProjectEuler #15) using backtracking.I've played around with it but the answer is always None. Any help would be appreciated(I know it can be solved using recursion or memoization but i want to solve it using backtracking)
def isvalid(maze,n,x,y):
if x<0 or y<0 or x>n or y>n :
return False
else: return True
def countPaths(maze,x,y,n,used,count):
if x==n-1 or y==n-1:
count+=1
return
if isvalid(maze,n,x,y):
used[x][y]=True
if (x+1<n and used[x+1][y]==False):
countPaths(maze,x+1,y,n,used,count)
if (x-1>0 and used[x-1][y]==False):
countPaths(maze,x-1,y,n,used,count)
if (y+1<n and used[x][y+1]==False):
countPaths(maze,x,y+1,n,used,count)
if (y-1>0 and used[x][y-1]==False):
countPaths(maze,x,y-1,n,used,count)
used[x][y]=False
return
Since in the base case, you are only returning 1 whenever end of row or column occurs it would yield wrong answer.
You should increment a counter signifying the number of times you are able to reach the final [n-1][n-1] i.e rightmost bottom cell.
bool isValid(int x, int y)
{
if (x < 0 || x >= n || y < 0 || y >= n)
return false;
return true;
}
void countPaths(int x, int y)
{
// cout << x << y << endl;
if (x == n - 1 && y == n - 1)
{
paths++;
return;
}
if (isValid(x, y))
{
visited[x][y] = true;
countPaths(x, y + 1);
countPaths(x + 1, y);
}
return;
}
Keeping paths & visited as global variables , I implemented the above approach.
For n=2 (1+1): 2
For n=3 (2+1): 6
For n=4 (3+1): 20
For n=5 (4+1): 70
however, this approach would not be viable for n=20.
I would suggest trying Dynamic Programming as it would simplify the process!

How to do it recursively if function depends on only one parameter

I need to do it with recursion, but the problem is that function depends on only ONE parameter and inside function it depends on two ( k and n ), also how to find minimum value if it returns only one value?
The function is :
I've already tried to make random k, but I don't think that is really good idea.
F1(int n) {
Random random = new Random();
int k = random.Next(1,10);
if (1 <= k && k <= n){
return Math.Min(F1(k - 1) + F1(n - k) + n);
} else {
return 0;
}
}
You need to make a loop traversing all k values in range 1..n. Something like this:
F1(int n) {
if (n == 0)
return ???? what is starting value?
minn = F1(0) + F1(n - 1) + n
for (int k = 2; k <= n; k++)
minn = Math.Min(minn, F1(k - 1) + F1(n - k) + n);
return minn;
}

Calculating a value to return using recursion

In this recursive method, I am trying to calculate a number using the initial call mystery5(-23, -48). After going through my first series of if statements, I get to the numbers 23 and 48. Once I get to the else branch of the decision statements, what precedence does the method call have in the equation? Also, does a negative sign in front of the mystery5 method call in the first two if statements indicate that there will be a positive x value if -23 is inserted into the method call (Ex: -mystery5(-23, -48))?
public int mystery5(int x, int y){
if (x < 0) {
return -mystery5(-x, y);
} else if (y < 0) {
return -mystery5(x, -y);
} else if (x == 0 && y == 0) {
return 0;
} else {
return 100 * mystery5(x / 10, y / 10) + 10 * (x % 10) + y % 10;
}
}
So it looks to me that mystery5(1, 0) returns 1. Assuming that is correct, then the call mystery5(-1, 0) would hit that first statement and it would see that x = -1) which is less than zero. This does return -mystery5(-x,y), so when the values for x and y are put in, this is equivalent to return -mystery5(1,0). The - in front of mystery5 flips the sign on the result of the mystery5 function when called. So when mystery5(1,0) returns a 1, that gets negated to -1. And that is the final return value of mystery5(-1,0).

sequence of numbers using recursion

I want to compute sequence of numbers like this:
n*(n-1)+n*(n-1)*(n-2)+n*(n-1)*(n-2)*(n-3)+n*(n-1)*(n-2)*(n-3)*(n-4)+...+n(n-1)...(n-n)
For example n=5 and sum equals 320.
I have a function, which compute one element:
int fac(int n, int s)
{
if (n > s)
return n*fac(n - 1, s);
return 1;
}
Recomputing the factorial for each summand is quite wasteful. Instead, I'd suggest to use memoization. If you reorder
n*(n-1) + n*(n-1)*(n-2) + n*(n-1)*(n-2)*(n-3) + n*(n-1)*(n-2)*(n-3)*...*1
you get
n*(n-1)*(n-2)*(n-3)*...*1 + n*(n-1)*(n-2)*(n-3) + n*(n-1)*(n-2) + n*(n-1)
Notice how you start with the product of 1..n, then you add the product of 1..n divided by 1, then you add the product divided by 1*2 etc.
I think a much more efficient definition of your function is (in Python):
def f(n):
p = product(range(1, n+1))
sum_ = p
for i in range(1, n-1):
p /= i
sum_ += p
return sum_
A recursive version of this definition is:
def f(n):
def go(sum_, i):
if i >= n-1:
return sum_
return sum_ + go(sum_ / i, i+1)
return go(product(range(1, n+1)), 1)
Last but not least, you can also define the function without any explicit recursion by using reduce to generate the list of summands (this is a more 'functional' -- as in functional programming -- style):
def f(n):
summands, _ = reduce(lambda (lst, p), i: (lst + [p], p / i),
range(1, n),
([], product(range(1, n+1))))
return sum(summands)
This style is very concise in functional programming languages such as Haskell; Haskell has a function call scanl which simplifies generating the summands so that the definition is just:
f n = sum $ scanl (/) (product [1..n]) [1..(n-2)]
Something like this?
function fac(int n, int s)
{
if (n >= s)
return n * fac(n - 1, s);
return 1;
}
int sum = 0;
int s = 4;
n = 5;
while(s > 0)
{
sum += fac(n, s);
s--;
}
print sum; //320
Loop-free version:
int fac(int n, int s)
{
if (n >= s)
return n * fac(n - 1, s);
return 1;
}
int compute(int n, int s, int sum = 0)
{
if(s > 0)
return compute(n, s - 1, sum + fac(n, s));
return sum;
}
print compute(5, 4); //320
Ok ther is not mutch to write. I would suggest 2 methodes if you want to solve this recursiv. (Becaus of the recrusiv faculty the complexity is a mess and runtime will increase drasticaly with big numbers!)
int func(int n){
return func(n, 2);
}
int func(int n, int i){
if (i < n){
return n*(fac(n-1,n-i)+func(n, i + 1));
}else return 0;
}
int fac(int i,int a){
if(i>a){
return i*fac(i-1, a);
}else return 1;
}

Resources