#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#define max 6
int coef[max];
int mat[max][max];
int m;
int r;
int n;
int t;
struct key
{
int x;
int y;
}ky[max];
struct lag_poly
{
float xc[max];
int y;
int x;
}lp[max+1];
int tmpx[max+1][max];
int tmp;
void in_dat()
{
n = max;
printf("\n Enter 't' : ");
scanf("%d",&t);
printf("\n Enter the secret 'm' : ");
scanf("%d",&m);
coef[0] = m;
for(int i=1;i<t;i++)
{
printf("\n Enter coefficient for x^%d : ",i);
scanf("%d",&coef[i]);
}
}
void make_ply()
{
int pw;
for(int i=0;i<n;i++)
{
ky[i].y = 0;
printf("\n\t Key %d\n Enter 'x%d': ",i+1,i);
scanf("%d",&ky[i].x);
for(int j=0;j<t;j++)
ky[i].y += (coef[j]*pow(ky[i].x,j));
printf("\n\t Key (x%d,y%d) : (%d,%d)",i,i,ky[i].x,ky[i].y);
}
getch();
}
void obt_ply(int opt)
{
tmp=0;
for(int i=0;i<t;i++)
{
if(i != opt)
{
tmpx[tmp][0] = (-1)*lp[i].x;
tmpx[tmp][1] = 1;
tmpx[tmp][2] = 0;
for(int j=3;j<max;j++)
tmpx[tmp][j] = 0;
printf("\n%d\n",tmp);
for(j=0;j<max;j++)
printf(" %d",tmpx[tmp][j]);
tmp++;
}
}
for(int j=0;j<max;j++)
tmpx[max][j] = 0;
printf("\n tmp=%d\n",tmp);
int in=0;
while(in < tmp-1)
{
for(i=0;i<max;i++)
{
for(j=0;j<max;j++)
{
tmpx[max][i+j] += (tmpx[in][i] * tmpx[in+1][j]);
}
}
printf("\n .. \n");
for(j=0;j<max;j++)
printf(" %d",tmpx[max][j]);
getch();
++in;
for(i=0;i<max;i++)
{
tmpx[in][i] = tmpx[max][i];
tmpx[max][i] = 0;
}
}
int prd = 1;
for(i=0;i<t;i++)
{
if(i != opt)
prd *= (lp[opt].x-lp[i].x);
}
printf("\n ..... res .......\n");
for(j=0;j<max;j++)
{
lp[opt].xc[j] = (float) tmpx[in][j]/prd;
printf(" %f",lp[opt].xc[j]);
}
}
void lagrange()
{
clrscr();
int op;
for(int i=0;i<t;i++)
{
printf("\n Enter Key to be regenerated :");
scanf("%d",&op);
lp[i].y = ky[op-1].y;
lp[i].x = ky[op-1].x;
for(int j=0;j<max;j++)
lp[i].xc[j] = 0.0;
}
for(i=0;i<t;i++)
obt_ply(i);
for(int j=0;j<max;j++)
lp[t].xc[j] = 0.0;
for(i=0;i<t;i++)
{
for(j=0;j<max;j++)
lp[t].xc[j] += (lp[i].y*lp[i].xc[j]);
}
getch();
printf("\n\n\n\n .. Ans ...\n\n");
for(j=0;j<max;j++)
printf(" %f",lp[t].xc[j]);
r = (int) (lp[t].xc[0]+0.5);
printf("\n %d\n",r);
}
void main()
{
clrscr();
in_dat();
make_ply();
lagrange();
getch();
}
No comments:
Post a Comment