Skip to content

Instantly share code, notes, and snippets.

@paranoidxc
Created May 21, 2014 09:38
Show Gist options
  • Save paranoidxc/3f6e48041501f3b4397c to your computer and use it in GitHub Desktop.
Save paranoidxc/3f6e48041501f3b4397c to your computer and use it in GitHub Desktop.
/*
(x+1)的N次方的多项式
*/
#include <stdio.h>
#include <stdlib.h>
#include "POLY.h"
main(int argc, char *argv[])
{ int N = atoi(argv[1]); float p = atof(argv[2]);
Poly t, x; int i, j;
printf("Binomial coefficients\n");
t = POLYadd(POLYterm(1, 1), POLYterm(1, 0));
for (i = 0, x = t; i < N; i++)
{ x = POLYmult(t, x); showPOLY(x); }
printf("%f\n", POLYeval(x, p));
}
-----
typedef struct poly *Poly;
void showPOLY(Poly);
Poly POLYterm(int, int);
Poly POLYadd(Poly, Poly);
Poly POLYmult(Poly, Poly);
float POLYeval(Poly, float);
-----
#include <stdlib.h>
#include "POLY.h"
struct poly { int N; int *a; };
Poly POLYterm(int coeff, int exp)
{ int i; Poly t = malloc(sizeof *t);
t->a = malloc((exp+1)*sizeof(int));
t->N = exp+1; t->a[exp] = coeff;
for (i = 0; i < exp; i++) t->a[i] = 0;
return t;
}
Poly POLYadd(Poly p, Poly q)
{ int i; Poly t;
if (p->N < q->N) { t = p; p = q; q = t; }
for (i = 0; i < q->N; i++) p->a[i] += q->a[i];
return p;
}
Poly POLYmult(Poly p, Poly q)
{ int i, j;
Poly t = POLYterm(0, (p->N-1)+(q->N-1));
for (i = 0; i < p->N; i++)
for (j = 0; j < q->N; j++)
t->a[i+j] += p->a[i]*q->a[j];
return t;
}
float POLYeval(Poly p, float x)
{ int i; double t = 0.0;
for (i = p->N-1; i >= 0; i--)
t = t*x + p->a[i];
return t;
}
@paranoidxc
Copy link
Author

缺少 showPOLY() 的实现,话说也没弄明白这个多项式是怎么计算的。
说是计算 (x+1) 的 N 次方,但是怎么和手算出来的不一样 - -!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment