Why does my recursive function in C cause a stack overflow? - c

I'm trying to make a function calculating x to the power n (where x could be a double, n must be an int). A recursive algorithm would be this one, but implementing it in C gave me the stack-overflow error.
I tried finding my answer here, but the closest I found was this, which didn't satisfy my needs.
Here is my code:
double power_adapted(double x, int n) {
if (n == 0)
return 1;
else if (n == 1)
return x;
else if (n % 2 == 0)
return power_adapted(power_adapted(x, n / 2), 2);
else
return x * power_adapted(power_adapted(x, (n - 1) / 2), 2);
}

The recursive calls always pass 2 as n, so they will always trigger another recursive call.
I think you misinterpreted the formula. I would interpret it as:
else if (n % 2 == 0) {
double v = power_adapted(x, n / 2);
return v * v;
}
else {
double v = power_adapted(x, (n - 1) / 2);
return x * (v * v);
}

I don't think what you're trying to accomplish makes sense.
If you take a look at this part of code,
else if (n % 2 == 0)
return power_adapted(power_adapted(x, n / 2), 2);
else
return power_adapted(power_adapted(x, (n - 1) / 2), 2);
While the nested calls may present no problem (as a statement), the call on the outside always has n = 2 and the base cases depend on n.
Solving the problem:
By taking a look at the formula provided, I think you should have a base case for n == 2 to return x * x (this is the simplest change to the algorithm). So, the algorithm could be stated as follows:
double power_adapted(double x, int n) {
if (n == 0)
return 1;
else if (n == 1)
return x;
else if (n == 2)
return x * x;
else if (n % 2 == 0)
return power_adapted(power_adapted(x, n / 2), 2);
else
return x * power_adapted(power_adapted(x, (n - 1) / 2), 2);
}

Related

Calculating a catalan number in C

I'm struggling with some code I have to write for an assignment in C. I have to calculate a Catalan number recursively.
The following formula is given:
Formula IMG.
The awnsers should be:
0 > 1 (Filling in 0 should print 1)
5 > 42 (Filling in 5 should print 42)
7 > 429 (Filling in 7 should print 429)
9 > 4862 (Filling in 9 should print 4862)
10 > 16796 (Filling in 10 should print 16796)
Please have a look at it:
#pragma warning(disable : 4996)
#include <stdio.h>
int catalanRecursief(int n) {
if (n == 0){
return 1;
} else {
return (2 * ((2 * n) - 1)) / (n + 1) * (catalanRecursief(n - 1));
}
}
int main(void){
int n;
printf("Catalan printer\n\n");
printf("What catalan number do you want to calculate? ");
scanf("%d", &n);
/*catalanRecursief(n);*/
printf("Catalan number: %d > %d", n, catalanRecursief(n));
getchar();
return(0);
}
By changing the unit from n to float it will be enough to solve it.
int catalanRecursief(float n) {
if (n == 0) {
return 1;
} else {
return ((2 * ((2 * n) - 1)) / (n + 1)) * (catalanRecursief(n - 1));
}
}
or also
int catalanRecursief(int n) {
if (n == 0) {
return 1;
} else {
return ((2.0 * ((2 * n) - 1)) / (n + 1)) * (catalanRecursief(n - 1));
}
}
this is because dividing int numbers c truncates them
As the theory says that Catalan numbers are integers, you should just ensure that the division happens last to avoid an integer division truncation:
...
else {
return (2 * ((2 * n) - 1)) * (catalanRecursief(n - 1)) / (n + 1);
}
...
With 32 bits integers, overflow is to be expected starting at C17, so use long long if you want to go further...

Writing a function that calculates the sum of squares within a range in one line in C

My try
double sum_squares_from(double x, double n){
return n<=0 ? 0 : x*x + sum_squares_from((x+n-1)*(x+n-1),n-1);
}
Instead of using loops my professor wants us to write functions like this...
What the exercise asks for is a function sum_squares_from() with double x being the starting number and n is the number of number. For example if you do x = 2 and n = 4 you get 2*2+3*3+4*4+5*5. It returns zero if n == 0.
My thinking was that in my example what I have is basically x*x+(x+1)(x+1)+(x+1+1)(x+1+1)+(x+1+1+1)(x+1+1+1) = (x+0)(x+0)+(x+1)(x+1)+(x+2)(x+2)+(x+3)(x+3) = (x+n-1)^2 repeated n times where n gets decremented every time by one until it becomes zero and then you sum everything.
Did I do it right?
(if my professor seems a bit demanding... he somehow does this sort of thing all in his head without auxiliary calculations. Scary guy)
It's not recursive, but it's one line:
int
sum_squares(int x, int n) {
return ((x + n - 1) * (x + n) * (2 * (x + n - 1) + 1) / 6) - ((x - 1) * x * (2 * (x - 1) + 1) / 6);
}
Sum of squares (of integers) has a closed-form solution for 1 .. n. This code calculates the sum of squares from 1 .. (x+n) and then subtracts the sum of squares from 1 .. (x-1).
The original version of this answer used ASCII art.
So,
&Sum;i:0..n i = n(n+1)(&half;)
&Sum;i:0..n i2 = n(n+1)(2n+1)(&frac16;)
We note that,
&Sum;i:0..n (x+i)2
&equals; &Sum;i:0...n x2 + 2xi + i2
&equals; (n+1)x2 + (2x)&Sum;i:0..n i + &Sum;i:0..n i2
&equals; (n+1)x2 + n(n+1)x + n(n+1)(2n+1)(&frac16;)
Thus, your sum has the closed form:
double sum_squares_from(double x, int n) {
return ((n-- > 0)
? (n + 1) * x * x
+ x * n * (n + 1)
+ n * (n + 1) * (2 * n + 1) / 6.
: 0);
}
If I apply some obfuscation, the one-line version becomes:
double sum_squares_from(double x, int n) {
return (n-->0)?(n+1)*(x*x+x*n+n*(2*n+1)/6.):0;
}
If the task is to implement the summation in a loop, use tail recursion. Tail recursion can be mechanically replaced with a loop, and many compilers implement this optimization.
static double sum_squares_from_loop(double x, int n, double s) {
return (n <= 0) ? s : sum_squares_from_loop(x+1, n-1, s+x*x);
}
double sum_squares_from(double x, int n) {
return sum_squares_from_loop(x, n, 0);
}
As an illustration, if you observe the generated assembly in GCC at a sufficient optimization level (-Os, -O2, or -O3), you will notice that the recursive call is eliminated (and sum_squares_from_loop is inlined to boot).
Try it online!
As mentioned in my original comment, n should not be type double, but instead be type int to avoid floating point comparison problems with n <= 0. Making the change and simplifying the multiplication and recursive call, you do:
double sum_squares_from(double x, int n)
{
return n <= 0 ? 0 : x * x + sum_squares_from (x + 1, n - 1);
}
If you think about starting with x * x and increasing x by 1, n times, then the simple x * x + sum_squares_from (x + 1, n - 1) is quite easy to understand.
Maybe this?
double sum_squares_from(double x, double n) {
return n <= 0 ? 0 : (x + n - 1) * (x + n - 1) + sum_squares_from(x, n - 1);
}

Program for finding nth root of the number without any external library or header like math.h

Is there any way to find nth root of the number without any external library in C? I'm working on a bare metal code so there is no OS. Also, no complete C is there.
You can write a program like this for nth root. This program is for square root.
int floorSqrt(int x)
{
// Base cases
if (x == 0 || x == 1)
return x;
// Staring from 1, try all numbers until
// i*i is greater than or equal to x.
int i = 1, result = 1;
while (result < x)
{
if (result == x)
return result;
i++;
result = i*i;
}
return i-1;
}
You can use the same approach for nth root.
Here there is a C implementation of the the nth root algorithm you can find in wikipedia. It needs an exponentiation algorithm, so I also include an implementation of a basic method for exponentiation by squaring that you can find also find in wikipedia.
double npower(double const base, int const n)
{
if (n < 0) return npower(1/base, -n)
else if (n == 0) return 1.0;
else if (n == 1) return base;
else if (n % 2) return base*npower(base*base, n/2);
else return npower(base*base, n/2);
}
double nroot(double const base, int const n)
{
if (n == 1) return base;
else if (n <= 0 || base < 0) return NAN;
else {
double delta, x = base/n;
do {
delta = (base/npower(x,n-1)-x)/n;
x += delta;
} while (fabs(delta) >= 1e-8);
return x;
}
}
Some comments on this:
The nth root algorithm in wikipedia leaves freedom for the initial guess. In this example I set it up to be base/n, but this was just a guess.
The macro NAN is usually defined in <math.h>, so you would need to define it to be suitable for your needs.
Both functions are implemented in a very rough and simple way, and their performance can be greatly improved with careful thought.
The tolerance in this example is set to 1e-8 and should be changed to something different. It should probably be proportional to the value of the base.
You can try the nth_root C function :
// return a number that, when multiplied by itself nth times, makes N.
unsigned nth_root(const unsigned n, const unsigned nth) {
unsigned a = n, b, c, r = nth ? n + (n > 1) : n == 1 ;
for (; a < r; b = a + (nth - 1) * r, a = b / nth)
for (r = a, a = n, c = nth - 1; c && (a /= r); --c);
return r;
}
Source

How does recursive function in C works

Function fun(n) is defined as such:
fun(n) = 1 (if n <=1)
fun(n) = fun(n/2) (if n is even)
fun(n) = 2*fun((n-1)/3) (if n> and n is odd)
I'm trying to write a recursive function to compute and return the result. I just started learning recursion, I got kind of lost while doing this function. Can someone correct me and explain to me? Thanks!
Here's what I did:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int fun(int n);
int main()
{
int num;
printf("\nEnter a number: ");
scanf("%d", num);
printf("Result = %d\n", fun(num));
return 0;
}
int fun(int n)
{
if (n <= 1)
{
return 1;
}
else if (n % 2 == 0)
{
return fun(n / 2);
}
else if ((n > 1) && (n % 2 == 0))
{
return 2 * fun((n - 1) / 3);
}
}
Expected output:
Enter a number: 13
Result = 2
Enter a number: 34
Result = 4
Output I'm getting instead:
Enter a number: 13
Result = 1
Enter a number: 34
Result = 1
scanf takes a pointer to int as argument for %d, i.e.,
scanf("%d", &num);
Also, your function fun does not handle all cases and may fall off the bottom:
if (n <= 1)
{
return 1;
}
else if (n % 2 == 0)
{
return fun(n / 2);
}
else if ((n > 1) && (n % 2 == 0))
{
return 2 * fun((n - 1) / 3);
}
The last else if condition is never met, because the previous check for n % 2 == 0 already returns in that case. Also the n > 1 is pointless because the first n <= 1 returns in all other cases.
You can simply make it:
else
{
return 2 * fun((n - 1) / 3);
}
The culprit is the last else if condition. Change it to:
else if ((n % 2) != 0)
The condition that n is odd is written wrong here. You wrote the same thing as for when n is even.
Its probably better to explicitly make the cases disjoint so you always return and there's no warning, like this:
int fun(int n)
{
if(n <= 1)
return 1;
if(n % 2 == 0)
return fun(n/2);
//No need for a condition, we know the last one must be satisfied
return 2 * fun((n-1)/3);
}
or, add another "default" case that indicates there was some error.
I think last if should be:
else if ((n > 1) && (n % 2 != 0))
Notice the != instead of ==.
The third condition
else if ((n > 1) && (n % 2 == 0))
is wrong, but instead of fixing it just you else no else if - because all other conditions were checked already.

Algorithm to find nth root of a number

I am looking for an efficient algorithm to find nth root of a number. The answer must be an integer. I have found that newtons method and bisection method are popular methods. Are there any efficient and simple methods for integer output?
#include <math.h>
inline int root(int input, int n)
{
return round(pow(input, 1./n));
}
This works for pretty much the whole integer range (as IEEE754 8-byte doubles can represent the whole 32-bit int range exactly, which are the representations and sizes that are used on pretty much every system). And I doubt any integer based algorithm is faster on non-ancient hardware. Including ARM. Embedded controllers (the microwave washing machine kind) might not have floating point hardware though. But that part of the question was underspecified.
I know this thread is probably dead, but I don't see any answers I like and that bugs me...
int root(int a, int n) {
int v = 1, bit, tp, t;
if (n == 0) return 0; //error: zeroth root is indeterminate!
if (n == 1) return a;
tp = iPow(v,n);
while (tp < a) { // first power of two such that v**n >= a
v <<= 1;
tp = iPow(v,n);
}
if (tp == a) return v; // answer is a power of two
v >>= 1;
bit = v >> 1;
tp = iPow(v, n); // v is highest power of two such that v**n < a
while (a > tp) {
v += bit; // add bit to value
t = iPow(v, n);
if (t > a) v -= bit; // did we add too much?
else tp = t;
if ( (bit >>= 1) == 0) break;
}
return v; // closest integer such that v**n <= a
}
// used by root function...
int iPow(int a, int e) {
int r = 1;
if (e == 0) return r;
while (e != 0) {
if ((e & 1) == 1) r *= a;
e >>= 1;
a *= a;
}
return r;
}
This method will also work with arbitrary precision fixed point math in case you want to compute something like sqrt(2) to 100 decimal places...
I question your use of "algorithm" when speaking of C programs. Programs and algorithms are not the same (an algorithm is mathematical; a C program is expected to be implementing some algorithm).
But on current processors (like in recent x86-64 laptops or desktops) the FPU is doing fairly well. I guess (but did not benchmark) that a fast way of computing the n-th root could be,
inline unsigned root(unsigned x, unsigned n) {
switch (n) {
case 0: return 1;
case 1: return x;
case 2: return (unsigned)sqrt((double)x);
case 3: return (unsigned)cbrt((double)x);
default: return (unsigned) pow (x, 1.0/n);
}
}
(I made a switch because many processors have hardware to compute sqrt and some have hardware to compute cbrt ..., so you should prefer these when relevant...).
I am not sure that n-th root of a negative number makes sense in general. So my root function takes some unsigned x and returns some unsigned number.  
Here is an efficient general implementation in C, using a simplified version of the "shifting nth root algorithm" to compute the floor of the nth root of x:
uint64_t iroot(const uint64_t x, const unsigned n)
{
if ((x == 0) || (n == 0)) return 0;
if (n == 1) return x;
uint64_t r = 1;
for (int s = ((ilog2(x) / n) * n) - n; s >= 0; s -= n)
{
r <<= 1;
r |= (ipow(r|1, n) <= (x >> s));
}
return r;
}
It needs this function to compute the nth power of x (using the method of exponentiation by squaring):
uint64_t ipow(uint64_t x, unsigned n)
{
if (x <= 1) return x;
uint64_t y = 1;
for (; n != 0; n >>= 1, x *= x)
if (n & 1)
y *= x;
return y;
}
and this function to compute the floor of base-2 logarithm of x:
int ilog2(uint64_t x)
{
#if __has_builtin(__builtin_clzll)
return 63 - ((x != 0) * (int)__builtin_clzll(x)) - ((x == 0) * 64);
#else
int y = -(x == 0);
for (unsigned k = 64 / 2; k != 0; k /= 2)
if ((x >> k) != 0)
{ x >>= k; y += k; }
return y;
#endif
}
Note: This assumes that your compiler understands GCC's __has_builtin test and that your compiler's uint64_t type is the same size as an unsigned long long.
You can try this C function to get the nth_root of an unsigned integer :
unsigned initial_guess_nth_root(unsigned n, unsigned nth){
unsigned res = 1;
for(; n >>= 1; ++res);
return nth ? 1 << (res + nth - 1) / nth : 0 ;
}
// return a number that, when multiplied by itself nth times, makes N.
unsigned nth_root(const unsigned n, const unsigned nth) {
unsigned a = initial_guess_nth_root(n , nth), b, c, r = nth ? a + (n > 0) : n == 1 ;
for (; a < r; b = a + (nth - 1) * r, a = b / nth)
for (r = a, a = n, c = nth - 1; c && (a /= r); --c);
return r;
}
Example of output :
24 == (int) pow(15625, 1.0/3)
25 == nth_root(15625, 3)
0 == nth_root(0, 0)
1 == nth_root(1, 0)
4 == nth_root(4096, 6)
13 == nth_root(18446744073709551614, 17) // 64-bit 20 digits
11 == nth_root(340282366920938463463374607431768211454, 37) // 128-bit 39 digits
Here is the github source.

Resources