Understanding recurrence relations with function calls inside loops - loops

int fun (int n)
{
int x=1, k;
if (n==1) return x;
for (k=1; k<n; ++k)
x = x + fun(k) * fun(n – k);
return x;
}
The recurrence relation in the solution is given as :
Solving this is easy, I got the answer to be 51.
The doubt is why the '1' (underlined in red) is outside the summation?
I understand if it were asymptotic analysis, we would consider it constant time because we only need to know the nature of growth, but since here we need an accurate answer.
Since this line x + fun(k) * fun(n – k) in inside the loop, x also loops, so why is it outside summation?

Most running sums begin at 0. However, this one begins at 1. That constant value is the one you underlined. It comes from the line
int x=1, k;

For each 'k' in for loop, x is getting replaced for the previous iteration value of x. Thus there wont be addition of the variable x but simply substitution.
consider f(3),
for k =1,
x=x+f(1)*f(2)....1
again loop runs,
k=2
x=x+f(2)*f(1)....2
substituting x from 1,
x=x+f(2)*f(1)+f(1)*f(2).
Carry out the same for everything.. and substitute x= 1 at end.. u will get the
GENERALIZED EQUATION YOU HAVE GIVEN.

Related

Why does my approximation of Exponential using Taylor Series expansion return "inf"?

This is my homework:
I haven't tried to write the part of Natural Logarithm because I can't solve the part of Exponential.
This is the the approximations of Exponential in C using Taylor Series expansion I wrote.
However, it returns inf. What did I do wrong?
#include <stdio.h>
// Returns approximate value of e^x
// using sum of first n terms of Taylor Series
float exponential(int n, float x)
{
float sum = 1.0f; // initialize sum of series
for (int a = n; a >= 0; ++a ) {
while (x * sum / a < 0.00001) {
break;
}
sum = 1 + x * sum / a;
return sum;
}
}
int main()
{
int n = 0;
float x = 1.0f;
printf("e^x = %.5f", exponential(n, x));
return 0;
}
With How do I ask and answer homework questions? in mind, I will give you a few things to have a careful look at.
From comment by Spektre:
from a quick look you are dividing by zero in while (x * sum / a < 0.00001) during first iteration of for loop as a=n and you called the function with n=0 ... also your code does not match the expansion for e^x at all
Have a look at the for loop:
for (int a = n; a >= 0; ++a )
What is the first value of a? The second? The third?
Keep in mind that the values are determined by ++a.
When will that loop end? It is determined by a >= 0. When is that false?
What is this loop doing?
while (x * sum / a < 0.00001) {
break;
}
I suspect that you programmed "English to C", as "do the outer loop while ...", which is practically from the assignment.
But the loop does something else. Apart from risking the division by 0 mentioned above, if the condition is true it will stay true and cause an endless loop, which then however is immediatly canceled in the first iteration.
The head of your function float exponential(int n, float x) expects n as a parameter. In main you init it with 0. I suspect you are unclear about where that value n is supposed to come from. In fact it is unknown. It is more a result of the calculation than an input.
You are supposed to add up until something happens.
You do not actually ever need the value of n. This means that your for loop is meaningless. The inner loop (though currently pointless) is much closer to your goal.
I will leave it at this for now. Try to use this input.
Feel free to edit the code in your question with improvements.
(Normally that is not appreciated, but in case of homework dialog questions I am fine with it.)
Your current implementation attempt is quite a bit off. Therefore I will describe how you should approach calculating such a series as given in your quesiton.
Let's look at your first formula:
You need to sum up terms e(n) = x^n / n!
To check with your series: 1 == x^0 / 0! - x == x^1 / 1! - ...
To calculate these terms, you need a simple rule how to get from e(n) to e(n+1). Looking at the formula above we see that you can use this rule:
e(n+1) = e(n) * x / (n+1)
Then you need to create a loop around that and sum up all the bits & pieces.
You are clearly not supposed to calculate x^n/n! from scratch in each iteration.
Your condition to stop the loop is when you reach the limit of 1e-5. The limit is for the new e(n+1), not for the sum.
For the other formulas you can use the same approach to find a rule how to calculate the single terms.
You might need to multiply the value by -1 in each step or do something like *x*n/(n+1) instead of *x/(n+1) etc.
Maybe you need to add some check if the formula is supposed to converge. Then maybe print some error message. This part is not clear in your question.
As this is homework, I only point into the direction and leave the implementation work to you.
If you have problems with implementation, I suggest to create a new question.
#include <stdio.h>
int main() {
float power;
printf("Enter the power of e\n");
scanf("%f", &power);
float ans = 1;
float temp = 1;
int i = 1;
while ((temp * power) / i >= 0.00001) {
temp = (temp * power) / i;
ans = ans + temp;
i++;
}
printf("%.5f", ans);
return 0;
}
I think I solved the problem
But the part about Natural Log is not solved, I will try.

Why am I getting this single output wrong?

I'm new to competitive programming and I participated in Codeforces #653 in which I spent the whole time solving this problem and did not submit any code because of exceeded time limits or wrong answer for test cases.
I wanted to solve this problem - https://codeforces.com/contest/1374/problem/A
You are given three integers x,y and n. Your task is to find the maximum integer k such that 0 ≤k≤ n that k mod x=y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x,y and n you need to find the maximum possible integer from 0 to n that has the remainder y modulo x
You have to answer t independent test cases. It is guaranteed that such k exists for each test case.
I wrote this following code:
#include <stdio.h>
int main(){
int i,t,j,k=0;
int x[60000],y[60000],n[60000],prev[60000];
scanf("%d",&t);
for(i=0; i<t; i++){
scanf("%d %d %d",&x[i],&y[i],&n[i]);
}
for(i=0; i<t; i++){
for(j=0, k=0; j<n[i]; j++ , k++){
if(j%x[i]==y[i]){
prev[i]=k;
}
}
}
for(i=0; i<t; i++){
printf("%d",prev[i]);
printf("\n");
}
return 0;
}
Everything was working fine but for some test cases I'm getting different answers.
This was the expected output
12339
0
15
54306
999999995
185
999999998
and my output was this:
12339
0
5
54306
999999995
185
999999998
I did not understand why I got 5 instead of 15 keeping all the other outputs correct and also could anyone please help me to optimize the code, its taking too long to compile for large inputs.
For the 1st part of your question, why the answer is wrong - has been answered nicely by others already. For the 2nd part about efficiency, the solution doesn't need any extra loop except the loop for iterating over the test case.
The solution could be as easy as this:
k = n - ((n - y) % x)
For example:x = 7, y = 5, n = 12345. Then,
k = 12345 - ((12345 - 5) % 7)
= 12339
This small piece of code could get you accepted:
#include <stdio.h>
int main()
{
int t, x, y, n;
scanf("%d", &t);
while (t > 0) {
scanf("%d %d %d", &x, &y, &n);
printf("%d\n", n - ((n - y) % x));
t--;
}
}
The reason you were getting TLE was because your code was taking too long. As I can see n could be upto 10^9 and so a O(N) solution would easily time-out at such constraints. Add to that, the fact that your code would be given upto 5*10^4 test cases. So, for your code to work, it should be much faster than O(N) time complexity. I have explained a better approach below which would satisfy the given constraints.
Optimised Approach :
For each test case, we are given x, y, n. And we have to find the largest number( let's say ans) between 0 to n such that ans%x = y.
Let's first find the remainder when we divide n by x. So, remainder = n%x. Now, if the remainder >= y, this means that we would have to reduce n such that it will leave a smaller remainder that is => a remainder equal to y. For this, we can simply reduce n by (remainder - y) amount.
Example :
For better understanding, lets see an example where
x = 10, y = 5, n = 16.
In this case remainder = n%x = 6. Now remainder > y, so we can just reduce our n by (remainder - y), that is n now becomes 15. We see that 15%x = y and so that's our answer.
The other case we might get is remainder < y. In this case, we have to increase the remainder. But we can't increase n (since it is the upper limit). So, what we can instead do is subtract x from n. The remainder will still be same. But now we are allowed to increase n by some amount which results in remainder to be y. For that we simply increase n by an amount y - remainder, so that new remainder will be equal to y.
Example :
Let's consider example where
x = 10, y = 5 and n = 24
Here, remainder = n%x = 4. So remainder < y. We subtract x from n, so n becomes 14 but still n%x = 4, so remainder remains same. But, we now have the advantage that we can increase x so that remainder would be equal to y. Since our remainder is 1 less than required (y), we increase n by 1 (or y - remainder = 1). Thus, we have the answer = 15.
This approach has time complexity of O(1) which is far better than O(N) approach. I hope that you got the idea of the approach I was trying to explain. Below is the pseudocode for same -
Pseudocode
remainder = n%x
if (remainder >= y) // Case 1
return n - ( remainder - y ) as the answer
else // Case 2
return ( n - x ) + ( y - remainder ) as the answer
Hope this helps !
The first part of this answer will explain what's wrong in your logic. The second part will contain a plot twist.
How to get the correct answer
As you have correctly been told in comments by #ErichKitzmueller your inner loop searches k values in the range [0-n[. In other words, if you are not familiar to my mathematical notation, you are not even considering the value n that is not included in your loop search, as you do for(j=0, k=0; j<n[i]; j++ , k++).
For the record, [0-n[ means "range from to 0 to n including 0 and not including n.
If you have to search the maximum value satisfying a given requirement... why starting counting from 0? You just need starting from the right limit of the range and loop backwards. The first k you will find satisfying the condition will be your output, so you'll just need to save it and exit the inner loop.
No need to find ALL the numbers satisfying the condition and overwrite them until the last is found (as you do).
The main loop of your solution would become something like that:
for(i=0; i<t; i++){
int found = 0;
for(k=n[i]; k>=0 && found==0; k--)
{
if( ( k % x[i] ) == y[i] )
{
prev[i] = k;
found = 1;
}
}
}
The plot twist (the REAL solution)
The previous solution will lead to correct answers... anyway it will be rejected as it exceeds the time limit.
Actually, all these competitive coding problems are all based on asking for a problem that in some way is simpler than it looks. In other words, it's always possible to find a way (usually after a mathematical analysis) that have a lower computational complexity than the one of the first solution that comes to your mind.
In this case we have to think:
What is the reminder of a division? y = k%x = k - x*int(k/x)
When has this expression its max? When k=n. So y = k - x*int(n/x)
So k = x*int(n/x) + y
Finally, we want make sure that this number is lower than n. If it is, we subtract x
The code becomes something like this:
#include <stdio.h>
int main(){
int i, t;
int x[60000],y[60000],n[60000],k[60000];
scanf("%d",&t);
for(i=0; i<t; i++){
scanf("%d %d %d",&x[i],&y[i],&n[i]);
}
for(i=0; i<t; i++){
int div = n[i] / x[i]; // Since div is an integer, only the integer part of the division is stored to div
k[i] = x[i] * div + y[i];
if( k[i] > n[i] )
k[i] -= x[i];
}
for(i=0; i<t; i++){
printf("%d", k[i]);
printf("\n");
}
return 0;
}
I've tested the solution on Codeforce, and it has been accepted.
the following proposed code:
cleanly compiles
performs the desired functionality
is very quick (could be made quicker via different I/O functions)
and now, the proposed code:
#include <stdio.h>
int main()
{
int x;
int y;
int n;
size_t t;
scanf("%zu",&t);
for( ; t; t-- )
{
scanf( "%d %d %d", &x, &y, &n );
printf( "%d\n", n - ((n - y) % x) );
}
return 0;
}

Factorial Function in C

I recently started reading Hacking: The Art of Exploitation by Jon Erickson. In the book he has the following function, which I will refer to as (A):
int factorial (int x) // .......... 1
{ // .......... 2
int i; // .......... 3
for (i = 1; i < x; i++) // .......... 4
x *= i; // .......... 5
return x; // .......... 6
} // .......... 7
This particular function is on pg. 17. Up until this function, I have understood everything he has described. To be fair, he has explained all of the elements within (A) in detail, with the exception of the return concept. However, I just don't see how (A) is suppose to describe the process of
x! = x * (x-1) * (x-2) * (x-3)
etc which I will refer to as (B). If someone could take the time to break this down in detail I would really appreciate it. Since I am asking for your help, I will go through the elements I believe I understand in order to potentially expose elements I believe I understand but actually do not but also to help you help me make the leap from how (A) is suppose to be a representation of (B).
Ok, so here is what I believe I understand.
In line 1, in (int x), x is being assigned the type integer. What I am less sure about is whether in factorial (int x), int x is being assigned the type factorial, or if even factorial is a type.
Line 3 is simple; i is being assigned the type integer.
Line 4 I am less confident on but I think I have a decent grasp of it. I'm assuming line 4 is a while-control structure with a counter. In the first segment, the counter is referred to as i and it's initial value is established as 1. I believe the second segment of line 4, i < x, dictates that while counter i is less than x, keep looping. The third segment, i++, communicates that for every valid loop/iteration of this "while a, then b" situation, you add 1 to i.
In line 5 I believe that x *= i is suppose to be shorthand for i * x but if I didn't know that this function is suppose to explain the process of calculating a factorial, I wouldn't be able to organically explain how lines 4 and 5 are suppose to interact.
'I humbly ask for your help. For any one who helps me get over this hump, I thank you in advance. '
I think the program given in the book is wrong. Theoretically, the for-loop will never terminate, as x is growing in every iteration, and much faster than i.
In practice, x will overflow after some time, thus terminating the loop.
Forget about why this calculates the factorial for a moment. First let's figure out what it does:
int factorial (int x) // .......... 1
{ // .......... 2
int i; // .......... 3
for (i = 1; i < x; i++) // .......... 4
x *= i; // .......... 5
return x; // .......... 6
} // .......... 7
Line 1:
Ignoring the part in the parenthesis for now, the line says int factorial (...) - that means this is a function called factorial and it has a type of int. The bit inside the parenthesis says int x - that means the function takes a parameter that will be called x and is of type int. A function can take multiple parameters separated by commas but this function takes only one.
Line 3:
We are creating a variable which we will call i of type int. The variable will only exist inside these curly braces so when the function is finished i will not exist any more.
Line 4:
This is indeed a looping control that uses the variable i created on line 3 to keep the count. At the start of the loop, the i=1 makes sure the count starts at 1. The i<x means it will keep looping as long as i is less than x. The i++ means each time the loop finishes the stuff in the curly braces the variable i will be incremented. The important part of this line is that the loops stops when i gets to x - which, as we will see, never happens.
Line 5:
The x*=i means the value of x will be updated by multiplying it by i. This will happen each time the loop iterates. So, for example, if x was equal to 5 the loop will make i equal to the values 1, 2, 3 and 4 (the numbers from 1 up but less than x) and the value of x will be updated by multiplying it by 1, 2, 3 and 4, making it larger and larger. But now that x is larger, the loop doesn't end here as expected - in fact, it contines looping making x larger and larger until the value of x no longer fits into an int. At that point, the program has undefined behaviour. Because compilers assume no one would want undefined behaviour, the program can do absolutely anything at that point including crashing or looping infinitely or even rewriting the whole program so it doesn't do any calculations at all.
Line 6:
We need to get that value of x back to the outside world and that is what the return command does - if the program gets to here the return statement gives the factorial function the value of x (which is the value of the factorial of 5 in the example we just used).
Then somewhere else in your program you might do this:
int f;
f = factorial(5);
Which will make the parameter called x have an initial value of 5 and will make f have the final value of the function.
So what does it return? Well, there is undefined behaviour so anything could happen - but because x gets larger and larger it definitely will NOT return the factorial. Anything could happen, but in my tests factorial(5) returns a huge negative number.
Try it online!
So how do we fix it? Well, as #JonathanLeffler said, we can't change the value of x so we need a new variable to hold the result. We will call that variable r:
int factorial (int x)
{
int r = 1;
for (int i = 1; i < x; i++)
r *= i;
return r;
}
So this program changes the value of r and doesn't change the value of x. So the loop works properly now. But it still doesn't calculate the factorial of the value passed in - if x is 5 it multiplies all the values up to but not including x.
Try it online!
So how do we fix it? The factorial has to include all the values including x, so this actually calculates the factorial:
int factorial (int x)
{
int r = 1;
for (int i = 1; i <= x; i++)
r *= i;
return r;
}
And this works as long as the value of x you pass in is small enough that the factorial can fit into a signed int.
Try it online!
You could get more range by using an unsigned long long but there is still a maximum value that can be calculated.
The program loops through integers 1 thru N-1. (Assume the input value is 'N')
Before loop starts, x=N.
After one iteration, x=N*1.
After 2 iterations, x=N*1*2.
After N-1 iterations, x=N*1*2*....(N-1).
Which is N factorial.
So N! is returned.
The fifth line is : x *= i;
You should understand here : x = x * i;
The loop will execute while i < x. Which means until reaches x - 1;
Knowing that i begins at 1 you will get this sum : x * 1 * 2 * 3 * ... * ( x - 1)
You can rearrange this so you get : 1 * 2 * 3 * ... * (x - 1) * x

how many times are the following functions called?

I have the following exercise program from a book. The book states that for values x=10 and y=100, functions; min, max, incr and square are called 1, 91, 90 and 90 respectively. However, to me it looks like they are being called the following number of times, 1, 1, 1 and 0. Can someone explain to me the book numbers. Thanks.
#include <stdio.h>
int min(int x, int y){
return x < y ? x : y;
}
int max(int x, int y){
return x > y ? y : x;
}
void incr(int *xp, int v) {
*xp += v;
}
int square (int x){
return x*x;
}
int main(void){
int i;
int x = 10;
int y = 100;
int t = 0;
for (i = min(x, y); i < max(x, y); incr(&i, 1)){
t += square(i);
printf("test %i", t);
}
}
It really depends on the compiler and optimisation settings.
Compiling this program (after fixing the max() function to return the maximum) with -O3 shows that none of the functions are actually called. The compiler can see that the loop goes from 10 to 100, and that the variable is incremented by 1.
Never assume that a function is called. You tell the compiler what you want the program to do, but the compiler can choose to do it any way it wants to.
By the way, without fixing max(), the compiler could see that this is an empty loop, and produced a main() function that simply returned without setting any variable or doing anything (again, with -O3).
Well the loop is really (as x and y don't change):
for (i = 10; i < 100; incr(&i, 1))
The the first statement executes only once - that's why min is executed 1 time.
The stop condition is executed once at the beginning and then after each iteration - so 91 times. The third statemnt is executed at the end of each iteration - so 90 times.
So the book is correct.
Feels like homework so I don't want to provide a full solution, but here's a hint... The key lies in understanding that max is evaluated (called) at the end of each loop iteration because the result of max can change after each loop iteration.
The loop will continue as long as i is less than max(x, y) for a given loop iteration.
In a for loop, there are 3 parts, initialization, continue condition, increment.
for(initialization; continue condition; increment) {
body;
}
The loop does this:
Do initialization part
Check continue condition (exit if true)
Execute code in body of for loop
Execute increment condition
Go back to 2
So if we walk through it, min is called once (initialization), and until the condition is met, max is called each time (continue condition). This will happen from i = 10 to i = y, which is 91 times (once at the beginning, and once at each iteration).
The increment part is called exactly once for each iteration, but not called initially, so it would get called 90 times (100 - 10).
The square function will happen the same number of times that increment is called (because it is called before increment, but once per iteration).
The second two expressions in a for loop are evaluated every time through the loop. The second expression is run every time to check if the loop should continue, and the last expression is intended to change the state of the loop. For example:
for (int x = 0; x < 100; ++x) { /* ... */ }
The x < 100 expression has to be evaluated each time through the loop to see if you changed it. The ++x needs to be evaluated every time because it's what's incrementing x.
The for (expression 1; expression 2; expression 3) loop is really just a shortcut for the common pattern:
{
expression 1;
if (expression 2)
{
do //Do-while + if to demonstrate how `break` and `continue` affect things
{
//loop body
expression 3;
}
while(expression 2)
}
}

Is my looping solution cheat for this puzzle?

This programming problem is #85 from a page of Microsoft interview questions. The complete problem description and my solution are posted below, but I wanted to ask my question first.
The rules say that you can loop for a fixed number of times. That is, if 'x' is a variable, you can loop over a block of code based on the value of 'x' at the time that you enter the loop. If 'x' changes during the loop, that won't change how many times you loop. Also, that is the only way to loop. You can't, for instance, loop until some condition is met.
In my solution to the problem, I have a loop which will be set to execute zero or more times. The problem is, in reality, it only ever executes 0 times or 1 time because the only statement in my loop is a return statement. So if we enter the loop, it only has a chance to run once. I am using this tactic instead of using an if-else block, because logical comparisons and if statements are not allowed. The rules don't explicitly say that you can't do this, but I am wondering if you would consider my solution invalid. I couldn't really figure out another way to do it.
So here are my questions:
Do you think my solution is invalid?
If so, did you think of another way to solve the problem?
Problem description:
85) You have an abstract computer, so just forget everything you know
about computers, this one only does what I'm about to tell you it
does. You can use as many variables as you need, there are no negative
numbers, all numbers are integers. You do not know the size of the
integers, they could be infinitely large, so you can't count on
truncating at any point. There are NO comparisons allowed, no if
statements or anything like that. There are only four operations you
can do on a variable.
You can set a variable to 0.
You can set a variable = another variable.
You can increment a variable (only by 1), and it's a post increment.
You can loop. So, if you were to say loop(v1) and v1 = 10, your loop would execute 10 times, but the value in v1 wouldn't change so
the first line in the loop can change value of v1 without changing the
number of times you loop.
You need to do 3 things.
Write a function that decrements by 1.
Write a function that subtracts one variable from another.
Write a function that divides one variable by another.
See if you can implement all 3 using at most 4 variables. Meaning, you're not making function calls now, you're making macros. And at
most you can have 4 variables. The restriction really only applies to
divide, the other 2 are easy to do with 4 vars or less. Division on
the other hand is dependent on the other 2 functions, so, if subtract
requires 3 variables, then divide only has 1 variable left unchanged
after a call to subtract. Basically, just make your function calls to
decrement and subtract so you pass your vars in by reference, and you
can't declare any new variables in a function, what you pass in is all
it gets.
My psuedocode solution (loop(x) means loop through this block of code x times):
// returns number - 1
int decrement(int number)
{
int previous = 0;
int i = 0;
loop(number)
{
previous = i;
i++;
}
return previous;
}
// returns number1 - number2
int subtract(int number1, int number2)
{
loop(number2)
{
number1= decrement(number1);
}
return number1;
}
//returns numerator/denominator
divide(int numerator, int denominator)
{
loop(subtract(numerator+1, denominator))
{
return (1 + divide(subtract(numerator, denominator), denominator));
}
return 0;
}
Here are C# methods that you can build and run. I had to make an artificial way for me to
satisfy the looping rules.
public int decrement(int num)
{
int previous = 0;
int LOOP = 0;
while (LOOP < num)
{
previous = LOOP;
LOOP++;
}
return previous;
}
public int subtract(int number1, int number2)
{
int LOOP = 0;
while (LOOP < number2)
{
number1 = decrement(number1);
LOOP++;
}
return number1;
}
public int divide(int numerator, int denominator)
{
int LOOP = 0;
while (LOOP < subtract(numerator+1, denominator))
{
return (1 + divide(subtract(numerator, denominator), denominator));
}
return 0;
}
Ok so the reason I think your answer might be invalid is because of how you use return. In fact I think just using the return is too much of an assumption. in a few places you use the return value of a function call as an extra variable. Now if the return statement is ok, then your answer is valid. The reason i think its not valid is because the problem hints at the fact that you need to think of these as macros, not function calls. Everything should be done by reference, you should change the variables and the return values are how you left those variables. Here is my solution:
int x, y, v, z;
//This function leaves x decremented by one and v equal to x
def decrement(x,v):
v=0;
loop(x):
x=v;
v++;
//this function leaves x decremented by y (x-y) and v equal to x
def subtract(x,y,v):
loop(y):
decrement(x,v);
//this function leaves x and z as the result of x divided by y, leaves y as is, and v as 0
//input of v and z dont matter, x should be greater than or equal to y or be 0, y should be greater than 0.
def divide(x,y,v,z):
z=0;
loop(x):
//these loops give us z+1 if x is >0 or leave z alone otherwise
loop(x):
z++;
decrement(x,v);
loop(x):
decrement(z,v)
//restore x
x++;
//reduce x by y until, when x is zero z will no longer increment
subtract(x,y,v);
//leave x as z so x is the result
x=z;

Resources