txt文件里面的多项式处理~~
现在txt文件有一个多元多项式, 3200*v45^6*v47^3 + 1876*v45^4*v47^6 + 3560*v45^5*v47^5 + 1120*v45^6*v47^4 + 272*v45^5*v47^6 + 208*v45^6*v47^5 + 16*v45^6*v47^6 + 2071387*v45^2*v48^2 + 1977269*v46^2*v47^2 + 725403*v45^2*v48^3 + 893531*v45^3*v48^2
想要把其中的系数为偶数的项去掉(奇数项保留),应该怎么做?
最后应该得到是 2071387*v45^2*v48^2 + 1977269*v46^2*v47^2 + 725403*v45^2*v48^3 + 893531*v45^3*v48^2 写回txt里面
可以考虑用模2
[解决办法]
struct Poly{
int m_nK;
std::string m_X;
int m_nPower;
Poly* m_pNext;
}
typedef Poly* PolyList;
读取多项式,放在这个连表里,然后遍历将m_nk为偶数的delete掉,然后将剩余链表写回
[解决办法]
一个简单高效的实现:
#include <ctype.h>#include <string.h>#include <stdio.h>#define ITEM_COUNT (32)#define ITEM_LEN (81)int isodd(char ch){ return ch == '1' || ch == '3' || ch == '5' || ch == '7' || ch == '9';}int main(int argc, char* argv[]){ FILE* file; char items[ITEM_COUNT][ITEM_LEN]; char last_char; int count = 0; int len = 0; int state = 0; char ch; int i; if((file = fopen("poly.txt", "rt")) == NULL) return -1; while(!feof(file)) { ch = fgetc(file); switch(state) { case 0: if(isdigit(ch)) { items[count][len++] = ch; state++; } break; case 1: if(isdigit(ch)) { items[count][len++] = ch; } else { if(!isodd(items[count][len - 1])) state = 0xff; else { items[count][len++] = ch; state++; } } break; case 2: if(isspace(ch)) { items[count][len] = '\0'; count++; len = 0; state = 0; } else items[count][len++] = ch; break; case 0xff: if(isspace(ch)) { len = 0; state = 0; } break; default: break; } } fclose(file); if((file = fopen("poly.txt", "wt")) == NULL) return -1; for(i = 0; i < count; i++) { if(i < count - 1) fprintf(file, "%s + ", items[i]); else fprintf(file, "%s", items[i]); } fclose(file); return 0;}
[解决办法]
字符挺有规律的,C++做的话,可以对Poly重载istream& operator>>和ostream& operator<<,轻轻松松