Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <list>
- using namespace std;
- static int offsets[2303];
- static int merge(int position, int mask) {
- return position << 8 | mask;
- }
- static bool is_bit_set(int mask, int position) {
- return ((mask >> position) & 1) == 1;
- }
- static int count_bits_left(int mask, int position) {
- int result = 0;
- for (int pos = 7; pos > position; pos--) {
- if (is_bit_set(mask, pos)) {
- result++;
- }
- }
- return result;
- }
- static void fill_offsets() {
- for (int position = 0; position < 8; position++) {
- for (int mask = 0; mask < 256; mask++) {
- int index = merge(position, mask);
- int value = count_bits_left(mask, position);
- offsets[index] = value;
- }
- }
- }
- class Polynom {
- private:
- int mask = 0;
- double* koeffs;
- public:
- Polynom (double , double , double , double , double , double , double , double );
- double get_koeff(int);
- void print(void);
- };
- Polynom::Polynom (double k7, double k6, double k5, double k4, double k3, double k2, double k1, double k0) {
- std::list<double> ks;
- int size = 0;
- if (k7 != 0) {
- mask |= (1 << 7);
- ks.push_back(k7);
- }
- if (k6 != 0) {
- mask |= (1 << 6);
- ks.push_back(k6);
- }
- if (k5 != 0) {
- mask |= (1 << 5);
- ks.push_back(k5);
- }
- if (k4 != 0) {
- mask |= (1 << 4);
- ks.push_back(k4);
- }
- if (k3 != 0) {
- mask |= (1 << 3);
- ks.push_back(k3);
- }
- if (k2 != 0) {
- mask |= (1 << 2);
- ks.push_back(k2);
- }
- if (k1 != 0) {
- mask |= (1 << 1);
- ks.push_back(k1);
- }
- if (k0 != 0) {
- mask |= (1 << 0);
- ks.push_back(k0);
- }
- koeffs = new double[ks.size()];
- int i = 0;
- for (double const &k: ks) {
- koeffs[i++] = k;
- }
- }
- double Polynom::get_koeff(int position) {
- if (!is_bit_set(mask, position)) {
- return 0.0;
- } else {
- int idx = merge(position, mask);
- int leftBits = offsets[idx];
- return koeffs[leftBits];
- }
- }
- void Polynom::print(){
- for (int i = 7; i >= 0; i--){
- cout << get_koeff(i) << "*x^" << i;
- if (i > 0){
- cout << " + ";
- }
- }
- cout << "\n";
- }
- int main()
- {
- fill_offsets();
- Polynom* p = new Polynom(1, 2, 3, 4, 5, 6, 7, 8);
- p->print();
- //1*x^7 + 2*x^6 + 3*x^5 + 4*x^4 + 5*x^3 + 6*x^2 + 7*x^1 + 8*x^0
- Polynom* p1 = new Polynom(1, 0, 0, 0, 0, 6, 0, 8);
- p1->print();
- //1*x^7 + 0*x^6 + 0*x^5 + 0*x^4 + 0*x^3 + 6*x^2 + 0*x^1 + 8*x^0
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement