Recursion - math formula, write a program - c

I need to implement this math formula in C:
I wrote a code:
#include <stdio.h>
int c(int n, int k)
{
if(k == 0)
return n;
if(c(n,k-1) % 2 == 0)
return c(n,k-1)/2;
if(c(n,k-1) % 2 != 0)
return c(n,k-1) * 3 + 1;
}
int main()
{
printf("%d", c(3,8));
return 0;
}
But I'm wondering if it was all about it? Does it work like it should? I must admit I have some troubles with calculating it on a paper ...

According to my calculation, the correct answer for n=3, k=8 should be 4, so your example should give you that. The program itself looks correct.
Update:
Here is how I do it on paper:
We're starting from c(0) - since in this case the value is known in any case:
c(0)=n=3
And go up, on each step choosing the calculation method based on evenness of the c(k-1):
c(1)=c(0)*3+1=10
c(2)=c(1)/2=5
c(3)=c(2)*3+1=16
c(4)=c(3)/2=8
c(5)=c(4)/2=4
c(6)=c(5)/2=2
c(7)=c(6)/2=1
c(8)=c(7)*3+1=4

Related

Why is my factorial program using recursion not working

I am new to coding. so I wanted to write a c program using recursion to calculate the factorial of a number.
#include <stdio.h>
int fact(int a) {
int n = 1;
if (a != 0)
return;
else
n = n * a;
a--;
fact(a);
return n;
}
int main() {
printf("%d", fact(5));
return 0;
}
This is the program I have written. I know this is probably wrong but I think I would understand programming better if I was able to understand why the above program is exactly wrong.
Because whenever you pass any value other than 0 to fact your code exits without even returning a value:
if(a!=0)
return;
You should get at least a warning from your compiler that this is invalid code, since fact is expected to always return an int value.
But even more so, this is a logical error.
Did you mean to write:
if (a == 0) return 1; //0! = 1
Lev M. pointed out your mistakes in his answer. This is a working recursive implementation of the factorial algorithm.
unsigned int fac(unsigned char n)
{
if (n == 0)
return 1;
return n * fac(n - 1);
}

Finding proper divisors in c

I'm trying to write a function that finds the number of divisors of a number n, which are smaller or equal to a number k using recursion (in C programming language).
For example, (9,3) should return 2 since the only positive divisors of 9 that are less than or equal to 3 are 1 and 3.
Here's what I've tried but can't figure out why it's not working:
int divisors(int n,int k){
int sum = 0;
if (k==0){
return 0;
}
else if (n%k==0){
return sum++ + divisors(n,k-1);
}
return sum;
}
If anyone is able to help I'd appreciate it.
You are almost there. I made a few fixes:
k == 1 as a break condition is faster, although k == 0 works fine.
The integer sum is useless.
When not counting, your thinking was almost correct. You should return 0 but for this specific case while keeping the function calculating the next ints (recursion). Therefore you should return 0 + divisors(n, k-1)
int divisors(int n,int k){
if (k == 1) return 1;
if (n % k == 0) return 1 + divisors(n, k-1);
return divisors(n, k-1);
}
You are not handling the resolution of the recursion properly
There is no need for a sum variable, instead you want to return the function call (or 0) in any case.
If you find a number so that n%k==0 holds true, you want to return 1 + the results of the next case. However, if you then find a number that is neither 0, nor a match it will stop, instead of checking all numbers down to 0. Therefore adjusting your code in the following way will solve the problem:
int divisors(int n,int k){
if (k==0)
return 0;
else if (n%k==0)
return divisors(n,k-1) + 1;
else
return divisors(n,k-1);
}

Recursion in C: why does my simple code doesn't work?

Given i the value of 3, the output should be the sum of 3/(3+1) + 2/(2+1) + 1/(1+1), always stopping on 1.
I can't seem to figure out what's wrong with what I did, thank you for your attention.
#include <stdio.h>
#include <math.h>
int sum_recur(int i) {
if (i > 1) {
return sum_recur(i - 1) / (sum_recur(i - 1) + 1);
} else {
return 1;
}
}
int main(void) {
int i;
printf("Inform a number:\n");
scanf("%d", &i);
printf("%d \n", sum_recur(i));
}
I think this would be the right recursive implementation of your formula
int sum_recur(int i){
if(i >= 1){
return (i / (i + 1)) + sum_recur(i-1);
} else{
return 0;
}
}
Also, as #atirit mentioned, you should consider making the output to be float or double in order to preserve the floating points values of the division result. Otherwise, the result of sum_recur will always be 0 since i / (i + 1) is always 0 for integer type
#include <stdio.h>
#include <math.h>
float sum_recur(int i){
if(i >= 1){
return (i / (i + 1.0)) + sum_recur(i-1);
} else{
return 0;
}
}
int main(void){
int i;
printf("Inform a number:\n");
scanf("%d",&i);
printf("%f \n",sum_recur(i));
}
Here's what I believe you're trying to implement, no need for recursion, but it's there if you need it:
#include <stdio.h>
double sum_recur(double i) {
if (i < 1) return 0;
return i / (i + 1) + sum_recur(i - 1);
}
double sum_iter(double i) {
double sum = 0;
for (; i >= 1; i--) {
sum += i / (i + 1);
}
return sum;
}
int main(void) {
int i;
printf("Inform a number:\n");
scanf("%d", &i);
printf("%f \n", sum_iter((double) i));
printf("%f \n", sum_recur((double) i));
}
The summary is this:
There's no need for the math library.
Use float or double and not int - in the code itself and in the printf.
Correct the logic in the recursion.
It can be solved iteratively quite nicely.
I don't understand what are you trying to achieve from this code. The code that you've written will always return 2.
sum_recur will always stop at 1 and you return statement will calculate 1/1+1, which is always 2. For input 3, the sum_recur will generate following:
sum_recur reaches 1 and hence returns 1 for input value 2
1/1 + 1 = 2, so for i=2 sum_recur will again return 2
This is will go on for any input number. This is why no matter what the input is, output of this recursion will always be 2. Further, what you expect this function to do in your question statement is not possible if you're using division between recursion calls. The result that you're looking to achieve is simply addition of 2 n-times or multiplication of 2 with n.
The answers written here explain the problem reasonably well, I just want to add a little bit on your code specifically,
While you do f(i-1)/f(i-1)+1 this is a terrible way of doing this and in case of a larger seed input this might cause you runtime problem with stackoverflow. So I suggest you should try something that's more efficient if at all you have to use recusion. Like this by storing the fun call value
int n = f(i-1);
return n/n +1;

Given the following series... the nth term of the series equals to (n - 1)th ^2 +1 and the first term of the series is 1 use recursion

Given the following series: 1, 2,5,26,677,
..... such that the nth term of the series equals to
(n-1)th ^2 +1 and the first term of the series is 1.
Write a program using recursive function named f to compute the nth term. Use for loop to print the
values of f
irst n terms in the series. You will take input n from the user.
Can anyone help me figure out what the hell I'm doing here? I am not sure how to do this with recursion, I know how to do it without.
Thanks,
t
EDIT: I've got it to do the sequence now, I just don't know how to fix it where there is a for loop that does the first 5 of this sequence and then the recursion function does the rest:
#include <stdio.h>
#include <math.h>
double f(double n);
int main(){
/*
Problem 6:
- Recursive function to generate nth term of f(x)
*/
double nth;
int i = 0,flag=1;
double result;
int seq[] = {1,2,5,26,677};
printf("Please enter the number of terms you would like to generate:
\n");
while(flag == 1){
if(scanf("%lf",&nth) == 1){
flag = 0;
}
else{
printf("Invalid number, program is exiting...\n");
return 0;
}
}
result = f(nth);
return 0;
}
double f(double n){
// base condition
if(n == 1)
return 1;
else
printf("(%.0lf)",pow(f(n-1),2.0) + 1);
}
You can do it in one line
#include <stdio.h>
size_t f(size_t nth) {
return nth == 1 ? 1 : f(nth - 1) * f(nth - 1) + 1;
}
int main() {
printf("%zu", f(5));
return 0;
}

SIGSEGV error on SPOJ

I would like to solve problem PRIME1 on SPOJ. When I run Code Blocks and input test examples, I get correct answer. But when I submit my code to SPOj, I get SIGSEGV error. Here is the explanation of this error on SPOJ:
SIGSEGV (signal 11) - the most common error for non-interpreted languages: a "segmentation fault" of the program. This may be caused e.g. by an out-of-scope array index causing a buffer overflow, an incorrectly initialized pointer, etc.
But I can't find this type of problem in my code. Could anyone help me, please?
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <math.h>
int prim(int n)
{
int s, i;
if (n == 1 || n == 2)
return 1;
if (n % 2 == 0)
return 0;
s = (int)sqrt(n);
for (i=3; i<=s; i+=2)
if (n % i == 0)
return 0;
return 1;
}
void print(int a,int b)
{
int *p,i,k;
int g;
g=(b/2);
p = (int *) malloc (sizeof(int)*(b-a+1));
for(i=0;i<(b-a+1);i++) p[i]=a+i;
for(i=0;i<=g;i++)
{
if(p[i] && prim(p[i]))
{
for(k=i*2+a;k<b-a;k+=i+a)
p[k]=0;
}
if(!prim(p[i]))
{
p[i]=0;
for(k=i*2+a;k<=b-a;k+=i+a)
p[k]=0;
}
}
for(i=0;i<(b-a+1);i++) if(p[i]!=0) printf("%d ",p[i]);
free(p);
}
int main(void)
{
int t,i,m,n;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&m,&n);
print(m,n);
}
return 0;
}
The problem is that g maybe greater than or equal to (b-a+1), depending on the test case. Since g = b/2 then for the array index i to not go out of bounds, b/2 < b-a+1 which implies that b/2 > a-1. That is not necessary. Since a can be say 6 and b can be like 7 according to the problem constraints.
Also according to the constraints, your code might well give TLE. Your algorithm is currently in the worst case O((n-m)*sqrt(n)), which I think is not enough to get AC in this question.
Read about Sieve of Eratosthenes and try to use it to solve this.

Resources