C.find an error in a very small program.Calculating the sum of the first k numbers of the sequence

Viewed 63

Calculating the sum of the first k numbers of the sequence a[0] = 1, a[k] = k*a[k-1] +1/k ( k = 1, 2, ... ).

UPD

There is still a problem with the recursive function ...What is the error?

#include <stdio.h>
#include <stdlib.h>
float m(float n){
    float k=1;
    float sum=k;
    int i;
    for (i=1; i<n;i++){
        k = (i*k+1.0/i);
        sum = sum+k;
    }
    return sum;
}

float Fn(float n)
{   
   if (n==0) {
   return 1;}
   
   return ((n*Fn(n-1)+1.0/n)+Fn(n-1));
  }

int main(int argc, char *argv[]) {
    float k;
printf("input k : ");
scanf("%f",&k);
printf("res %f \n",Fn(k));
    return 0;
}
1 Answers

There were several issues in your code:

  • Integer division: 1/n = 0
  • There was a confusion between the term value Fn and the sum value
  • An iterative solution is simpler here than a recursive one

Here is a code, with both iterative and recursive implementations:

#include <stdio.h>
#include <stdlib.h>

float sum_fn(int n){
    float Fk = 1;
    float sum = Fk;

    for (int i = 1; i <= n; i++){
        Fk = i*Fk + 1.0/i;
        sum += Fk;
    }
    return sum;
}

float sum_recursive(int n, float *sum){
    if (n == 0) {
        *sum += 1.0;
        return 1.0;
    }
   float Fn = n * sum_recursive(n-1, sum) + 1.0/n;
   *sum += Fn;
   return Fn;
}


int main(int argc, char *argv[]) {
    int k;
    printf("input k : ");
    scanf("%d", &k);
    printf("k = %d\tsum = %f\n", k, sum_fn(k));
    float sum = 0;
    sum_recursive(k, &sum);
    printf("k = %d\tsum = %f\n", k, sum);
    return 0;
}
Related