fork download
  1. #include <stdio.h>
  2.  
  3. typedef struct {
  4. float term;
  5. float sum;
  6. } A; // current term and sum of series A
  7.  
  8. void compute_A (int n, A * res)
  9. {
  10. int i;
  11. float anm1, // a[n-1]
  12. anm2; // a[n-2]
  13.  
  14. // special case for n<=1
  15. if (n == 1)
  16. {
  17. res->sum = res->term = 1;
  18. return;
  19. }
  20. if (n <= 0)
  21. {
  22. res->sum = res->term = 0;
  23. return;
  24. }
  25.  
  26. // initial terms
  27. anm2 = anm1 = 1;
  28.  
  29. // initial sum
  30. float sum = anm1+anm2;
  31.  
  32. // compute the remaining n-2 terms and cumulate the sum
  33. for (i = 2 ; i != n ; i++)
  34. {
  35. // curent term
  36. float an = ((8 * anm1*anm1) - 1)/anm2;
  37.  
  38. // cumulate sum
  39. sum += an;
  40.  
  41. // shift computation window
  42. anm2 = anm1;
  43. anm1 = an;
  44. printf ("index %d : term %g sum %g\n", i, an, sum);
  45. }
  46.  
  47. // report result
  48. res->sum = sum;
  49. res->term = anm1;
  50. }
  51.  
  52. int main (void)
  53. {
  54. int n;
  55. A res;
  56. printf("\nInput N of term an: ");
  57. scanf("%d",&n); printf("\n");
  58.  
  59. compute_A (n, &res);
  60.  
  61. printf("\na%d=%f",n,res.term);
  62. printf("\n\nS(%d)=%f",n,res.sum);
  63. }
Runtime error #stdin #stdout 0s 2296KB
stdin
9
stdout
Input N of term an: 
index 2 : term 7 sum 9
index 3 : term 391 sum 400
index 4 : term 174721 sum 175121
index 5 : term 6.24602e+08 sum 6.24777e+08
index 6 : term 1.78629e+13 sum 1.78635e+13
index 7 : term 4.08686e+18 sum 4.08688e+18
index 8 : term 7.48029e+24 sum 7.48029e+24

a9=7480289613705262181384192.000000

S(9)=7480293648930528305348608.000000