A finite field or Galois field (GF) has a finite number of elements, and has an order which is equal to a prime number (GF(\(p\))) or to the power of a prime number (GF(\(p^n\))). For example GF(\(2^n\)) has \(2^n\) elements, and its elements are known as binary polynomals (where the co-efficients of the polynomial factors either are either zero or one values. For example, a value of 10110 can be represented as \(x^4+x^2+x\). In this case we will add and multiply two polynomials.
Polynomials in Rust |
Method
If we have 19 (10011 = \(x^4+x+1\)) and 67 (1000011 - \(x^6+x+1\)), if we add:
\(x^4+x+1 + x^6+x+1 = x^6 + x^4 + 2x +2\)
For multiply:
\((x^4+x+1) \times (x^6+x+1) = x^{10}+x^7+x^6+x^5+x^4+x^2+x2+1\)
Code
First we create the Rust project with:
cargo new poly
We then go into the poly folder and then into the src folder, and edit the main.rs file with:
extern crate rustnomial; use std::str::FromStr; use std::env; use rustnomial::{Polynomial}; fn main() { let mut poly1=Polynomial::::from_str("x^2+x+1").unwrap(); let mut poly2=Polynomial:: ::from_str("x^5+x^3+1").unwrap(); let args: Vec = env::args().collect(); if args.len() >1 { poly1=Polynomial:: ::from_str(args[1].as_str()).unwrap();} if args.len() >2 { poly2=Polynomial:: ::from_str(args[2].as_str()).unwrap();} println!("Input: {}",poly1.clone()); println!("Input: {}",poly2.clone()); let mut res=poly1.clone()+poly2.clone(); println!("\n{}+{} = {}",poly1.clone(),poly2.clone(),res); res=poly1.clone()*poly2.clone(); println!("\n({})*({}) = {}",poly1.clone(),poly2.clone(),res); }
Finally we simply build with:
cargo build
For a run with \(a=19\) and \(b=67\):
cargo run 19 67
we get:
Input: x^10 + x^5 + x^2 + 1 Input: x^5 + x^3 + x^2 + 1 x^10 + x^5 + x^2 + 1+x^5 + x^3 + x^2 + 1=x^10 + 2x^5 + x^3 + 2x^2 + 2 (x^10 + x^5 + x^2 + 1)*(x^5 + x^3 + x^2 + 1)=x^15 + x^13 + x^12 + 2x^10 + x^8 + 2x^7 + 3x^5 + x^4 + x^3 + 2x^2 + 1