Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
70
Task/Hamming-numbers/Rust/hamming-numbers-1.rust
Normal file
70
Task/Hamming-numbers/Rust/hamming-numbers-1.rust
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
extern crate num;
|
||||
num::bigint::BigUint;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
fn basic_hamming(n: usize) -> BigUint {
|
||||
let two = BigUint::from(2u8);
|
||||
let three = BigUint::from(3u8);
|
||||
let five = BigUint::from(5u8);
|
||||
let mut h = vec![BigUint::from(0u8); n];
|
||||
h[0] = BigUint::from(1u8);
|
||||
let mut x2 = BigUint::from(2u8);
|
||||
let mut x3 = BigUint::from(3u8);
|
||||
let mut x5 = BigUint::from(5u8);
|
||||
let mut i = 0usize; let mut j = 0usize; let mut k = 0usize;
|
||||
|
||||
// BigUint comparisons are expensive, so do it only as necessary...
|
||||
fn min3(x: &BigUint, y: &BigUint, z: &BigUint) -> (usize, BigUint) {
|
||||
let (cs, r1) = if y == z { (0x6, y) }
|
||||
else if y < z { (2, y) } else { (4, z) };
|
||||
if x == r1 { (cs | 1, x.clone()) }
|
||||
else if x < r1 { (1, x.clone()) } else { (cs, r1.clone()) }
|
||||
}
|
||||
|
||||
let mut c = 1;
|
||||
while c < n { // satisfy borrow checker with extra blocks: { }
|
||||
let (cs, e1) = { min3(&x2, &x3, &x5) };
|
||||
h[c] = e1; // vector now owns the generated value
|
||||
if (cs & 1) != 0 { i += 1; x2 = &two * &h[i] }
|
||||
if (cs & 2) != 0 { j += 1; x3 = &three * &h[j] }
|
||||
if (cs & 4) != 0 { k += 1; x5 = &five * &h[k] }
|
||||
c += 1;
|
||||
}
|
||||
|
||||
match h.pop() {
|
||||
Some(v) => v,
|
||||
_ => panic!("basic_hamming: arg is zero; no elements")
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
print!("[");
|
||||
for (i, h) in (1..21).map(basic_hamming).enumerate() {
|
||||
if i != 0 { print!(",") }
|
||||
print!(" {}", h)
|
||||
}
|
||||
println!(" ]");
|
||||
println!("{}", basic_hamming(1691));
|
||||
|
||||
let strt = Instant::now();
|
||||
|
||||
let rslt = basic_hamming(1000000);
|
||||
|
||||
let elpsd = strt.elapsed();
|
||||
let secs = elpsd.as_secs();
|
||||
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
|
||||
let dur = secs * 1000 + millis;
|
||||
|
||||
let rs = rslt.to_str_radix(10);
|
||||
let mut s = rs.as_str();
|
||||
println!("{} digits:", s.len());
|
||||
while s.len() > 100 {
|
||||
let (f, r) = s.split_at(100);
|
||||
s = r;
|
||||
println!("{}", f);
|
||||
}
|
||||
println!("{}", s);
|
||||
|
||||
println!("This last took {} milliseconds", dur);
|
||||
}
|
||||
32
Task/Hamming-numbers/Rust/hamming-numbers-2.rust
Normal file
32
Task/Hamming-numbers/Rust/hamming-numbers-2.rust
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
fn nodups_hamming(n: usize) -> BigUint {
|
||||
let two = BigUint::from(2u8);
|
||||
let three = BigUint::from(3u8);
|
||||
let five = BigUint::from(5u8);
|
||||
let mut m = vec![BigUint::from(0u8); 1];
|
||||
m[0] = BigUint::from(1u8);
|
||||
let mut h = vec![BigUint::from(0u8); n];
|
||||
h[0] = BigUint::from(1u8);
|
||||
if n > 1 {
|
||||
m.push(BigUint::from(3u8)); // for initial x53 advance
|
||||
h[1] = BigUint::from(2u8); // for initial x532 advance
|
||||
}
|
||||
let mut x5 = BigUint::from(5u8);
|
||||
let mut x53 = BigUint::from(9u8); // 3 times 3 because already merged one step
|
||||
let mut mrg = BigUint::from(3u8);
|
||||
let mut x532 = BigUint::from(2u8);
|
||||
|
||||
let mut i = 0usize; let mut j = 1usize;
|
||||
let mut c = 1usize;
|
||||
while c < n { // satisfy borrow checker with extra blocks: { }
|
||||
if &x532 < &mrg { h[c] = x532; i += 1; x532 = &two * &h[i]; }
|
||||
else { h[c] = mrg;
|
||||
if &x53 < &x5 { mrg = x53; j += 1; x53 = &three * &m[j]; }
|
||||
else { mrg = x5.clone(); x5 = &five * &x5; };
|
||||
m.push(mrg.clone()); };
|
||||
c += 1;
|
||||
}
|
||||
match h.pop() {
|
||||
Some(v) => v,
|
||||
_ => panic!("nodups_hamming: arg is zero; no elements")
|
||||
}
|
||||
}
|
||||
83
Task/Hamming-numbers/Rust/hamming-numbers-3.rust
Normal file
83
Task/Hamming-numbers/Rust/hamming-numbers-3.rust
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
fn log_nodups_hamming(n: u64) -> BigUint {
|
||||
if n <= 0 { panic!("nodups_hamming: arg is zero; no elements") }
|
||||
if n < 2 { return BigUint::from(1u8) } // trivial case for n == 1
|
||||
if n > 1.2e13 as u64 { panic!("log_nodups_hamming: argument too large to guarantee results!") }
|
||||
|
||||
// constants as expanded integers to minimize round-off errors, and
|
||||
// reduce execution time using integer operations not float...
|
||||
const LAA2: u64 = 35184372088832; // 2.0f64.powi(45)).round() as u64;
|
||||
const LBA2: u64 = 55765910372219; // 3.0f64.log2() * 2.0f64.powi(45)).round() as u64;
|
||||
const LCA2: u64 = 81695582054030; // 5.0f64.log2() * 2.0f64.powi(45)).round() as u64;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Logelm { // log representation of an element with only allowable powers
|
||||
exp2: u16,
|
||||
exp3: u16,
|
||||
exp5: u16,
|
||||
logr: u64 // log representation used for comparison only - not exact
|
||||
}
|
||||
|
||||
impl Logelm {
|
||||
fn lte(&self, othr: &Logelm) -> bool {
|
||||
if self.logr <= othr.logr { true } else { false }
|
||||
}
|
||||
fn mul2(&self) -> Logelm {
|
||||
Logelm { exp2: self.exp2 + 1, logr: self.logr + LAA2, .. *self }
|
||||
}
|
||||
fn mul3(&self) -> Logelm {
|
||||
Logelm { exp3: self.exp3 + 1, logr: self.logr + LBA2, .. *self }
|
||||
}
|
||||
fn mul5(&self) -> Logelm {
|
||||
Logelm { exp5: self.exp5 + 1, logr: self.logr + LCA2, .. *self }
|
||||
}
|
||||
}
|
||||
|
||||
let one = Logelm { exp2: 0, exp3: 0, exp5: 0, logr: 0 };
|
||||
let mut x532 = one.mul2();
|
||||
let mut mrg = one.mul3();
|
||||
let mut x53 = one.mul3().mul3(); // advance as mrg has the former value...
|
||||
let mut x5 = one.mul5();
|
||||
|
||||
let mut h = Vec::with_capacity(65536); // vec!(one.clone(); 0);
|
||||
let mut m = Vec::<Logelm>::with_capacity(65536); // vec!(one.clone(); 0);
|
||||
|
||||
let mut i = 0usize; let mut j = 0usize;
|
||||
for _ in 1 .. n {
|
||||
let cph = h.capacity();
|
||||
if i > cph / 2 { // drain extra unneeded values...
|
||||
h.drain(0 .. i);
|
||||
i = 0;
|
||||
}
|
||||
if x532.lte(&mrg) {
|
||||
h.push(x532);
|
||||
x532 = h[i].mul2();
|
||||
i += 1;
|
||||
} else {
|
||||
h.push(mrg);
|
||||
if x53.lte(&x5) {
|
||||
mrg = x53;
|
||||
x53 = m[j].mul3();
|
||||
j += 1;
|
||||
} else {
|
||||
mrg = x5;
|
||||
x5 = x5.mul5();
|
||||
}
|
||||
let cpm = m.capacity();
|
||||
if j > cpm / 2 { // drain extra unneeded values...
|
||||
m.drain(0 .. j);
|
||||
j = 0;
|
||||
}
|
||||
m.push(mrg);
|
||||
}
|
||||
}
|
||||
|
||||
let o = &h[&h.len() - 1];
|
||||
let two = BigUint::from(2u8);
|
||||
let three = BigUint::from(3u8);
|
||||
let five = BigUint::from(5u8);
|
||||
let mut ob = BigUint::from(1u8); // convert to BigUint at the end
|
||||
for _ in 0 .. o.exp2 { ob = ob * &two }
|
||||
for _ in 0 .. o.exp3 { ob = ob * &three }
|
||||
for _ in 0 .. o.exp5 { ob = ob * &five }
|
||||
ob
|
||||
}
|
||||
131
Task/Hamming-numbers/Rust/hamming-numbers-4.rust
Normal file
131
Task/Hamming-numbers/Rust/hamming-numbers-4.rust
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
extern crate num; // requires dependency on the num library
|
||||
use num::bigint::BigUint;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
fn log_nodups_hamming_iter() -> Box<Iterator<Item = (u16, u16, u16)>> {
|
||||
// constants as expanded integers to minimize round-off errors, and
|
||||
// reduce execution time using integer operations not float...
|
||||
const LAA2: u64 = 35184372088832; // 2.0f64.powi(45)).round() as u64;
|
||||
const LBA2: u64 = 55765910372219; // 3.0f64.log2() * 2.0f64.powi(45)).round() as u64;
|
||||
const LCA2: u64 = 81695582054030; // 5.0f64.log2() * 2.0f64.powi(45)).round() as u64;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Logelm { // log representation of an element with only allowable powers
|
||||
exp2: u16,
|
||||
exp3: u16,
|
||||
exp5: u16,
|
||||
logr: u64 // log representation used for comparison only - not exact
|
||||
}
|
||||
impl Logelm {
|
||||
fn lte(&self, othr: &Logelm) -> bool {
|
||||
if self.logr <= othr.logr { true } else { false }
|
||||
}
|
||||
fn mul2(&self) -> Logelm {
|
||||
Logelm { exp2: self.exp2 + 1, logr: self.logr + LAA2, .. *self }
|
||||
}
|
||||
fn mul3(&self) -> Logelm {
|
||||
Logelm { exp3: self.exp3 + 1, logr: self.logr + LBA2, .. *self }
|
||||
}
|
||||
fn mul5(&self) -> Logelm {
|
||||
Logelm { exp5: self.exp5 + 1, logr: self.logr + LCA2, .. *self }
|
||||
}
|
||||
}
|
||||
|
||||
let one = Logelm { exp2: 0, exp3: 0, exp5: 0, logr: 0 };
|
||||
let mut x532 = one.mul2();
|
||||
let mut mrg = one.mul3();
|
||||
let mut x53 = one.mul3().mul3(); // advance as mrg has the former value...
|
||||
let mut x5 = one.mul5();
|
||||
|
||||
let mut h = Vec::with_capacity(65536);
|
||||
let mut m = Vec::<Logelm>::with_capacity(65536);
|
||||
|
||||
let mut i = 0usize; let mut j = 0usize;
|
||||
Box::new((0u64 .. ).map(move |it| if it < 1 { (0, 0, 0) } else {
|
||||
let cph = h.capacity();
|
||||
if i > cph / 2 {
|
||||
h.drain(0 .. i);
|
||||
i = 0;
|
||||
}
|
||||
if x532.lte(&mrg) {
|
||||
h.push(x532);
|
||||
x532 = h[i].mul2();
|
||||
i += 1;
|
||||
} else {
|
||||
h.push(mrg);
|
||||
if x53.lte(&x5) {
|
||||
mrg = x53;
|
||||
x53 = m[j].mul3();
|
||||
j += 1;
|
||||
} else {
|
||||
mrg = x5;
|
||||
x5 = x5.mul5();
|
||||
}
|
||||
let cpm = m.capacity();
|
||||
if j > cpm / 2 {
|
||||
m.drain(0 .. j);
|
||||
j = 0;
|
||||
}
|
||||
m.push(mrg);
|
||||
}
|
||||
let o = &h[&h.len() - 1];
|
||||
(o.exp2, o.exp3, o.exp5)
|
||||
}))
|
||||
}
|
||||
|
||||
fn convert_log2big(o: (u16, u16, u16)) -> BigUint {
|
||||
let two = BigUint::from(2u8);
|
||||
let three = BigUint::from(3u8);
|
||||
let five = BigUint::from(5u8);
|
||||
let (x2, x3, x5) = o;
|
||||
let mut ob = BigUint::from(1u8); // convert to BigUint at the end
|
||||
for _ in 0 .. x2 { ob = ob * &two }
|
||||
for _ in 0 .. x3 { ob = ob * &three }
|
||||
for _ in 0 .. x5 { ob = ob * &five }
|
||||
ob
|
||||
}
|
||||
|
||||
fn main() {
|
||||
print!("[");
|
||||
for (i, h) in log_nodups_hamming_iter().take(20).map(convert_log2big).enumerate() {
|
||||
if i != 0 { print!(",") }
|
||||
print!(" {}", h)
|
||||
}
|
||||
println!(" ]");
|
||||
println!("{}", convert_log2big(log_nodups_hamming_iter().take(1691).last().unwrap()));
|
||||
|
||||
let strt = Instant::now();
|
||||
|
||||
// let rslt = convert_log2big(log_nodups_hamming_iter().take(1000000000).last().unwrap());
|
||||
let mut it = log_nodups_hamming_iter().into_iter();
|
||||
for _ in 0 .. 100-1 { // a little faster; less one level of iteration
|
||||
let _ = it.next();
|
||||
}
|
||||
let rslt = convert_log2big(it.next().unwrap());
|
||||
|
||||
let elpsd = strt.elapsed();
|
||||
let secs = elpsd.as_secs();
|
||||
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
|
||||
let dur = secs * 1000 + millis;
|
||||
|
||||
println!("2^{} times 3^{} times 5^{}", rslt.0, rslt.1, rslt.2);
|
||||
let rs = convert_log2big(rslt).to_str_radix(10);
|
||||
let mut s = rs.as_str();
|
||||
println!("{} digits:", s.len());
|
||||
let lg3 = 3.0f64.log2();
|
||||
let lg5 = 5.0f64.log2();
|
||||
let lg = (rslt.0 as f64 + rslt.1 as f64 * lg3
|
||||
+ rslt.2 as f64 * lg5) * 2.0f64.log10();
|
||||
println!("Approximately {}E+{}", 10.0f64.powf(lg.fract()), lg.trunc());
|
||||
if s.len() <= 10000 {
|
||||
while s.len() > 100 {
|
||||
let (f, r) = s.split_at(100);
|
||||
s = r;
|
||||
println!("{}", f);
|
||||
}
|
||||
println!("{}", s);
|
||||
}
|
||||
|
||||
println!("This last took {} milliseconds.", dur);
|
||||
}
|
||||
247
Task/Hamming-numbers/Rust/hamming-numbers-5.rust
Normal file
247
Task/Hamming-numbers/Rust/hamming-numbers-5.rust
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
extern crate num;
|
||||
use num::bigint::BigUint;
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::cell::{UnsafeCell, RefCell};
|
||||
use std::mem;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
// implementation of Thunk closure here...
|
||||
|
||||
pub struct Thunk<'a, R>(Box<dyn FnOnce() -> R + 'a>);
|
||||
|
||||
impl<'a, R: 'a> Thunk<'a, R> {
|
||||
#[inline(always)]
|
||||
fn new<F: 'a + FnOnce() -> R>(func: F) -> Thunk<'a, R> {
|
||||
Thunk(Box::new(func))
|
||||
}
|
||||
#[inline(always)]
|
||||
fn invoke(self) -> R { self.0() }
|
||||
}
|
||||
|
||||
// actual Lazy implementation starts here...
|
||||
|
||||
use self::LazyState::*;
|
||||
|
||||
pub struct Lazy<'a, T: 'a>(UnsafeCell<LazyState<'a, T>>);
|
||||
|
||||
enum LazyState<'a, T: 'a> {
|
||||
Unevaluated(Thunk<'a, T>),
|
||||
EvaluationInProgress,
|
||||
Evaluated(T)
|
||||
}
|
||||
|
||||
impl<'a, T: 'a> Lazy<'a, T>{
|
||||
#[inline]
|
||||
pub fn new<'b, F>(thunk: F) -> Lazy<'b, T>
|
||||
where F: 'b + FnOnce() -> T {
|
||||
Lazy(UnsafeCell::new(Unevaluated(Thunk::new(thunk))))
|
||||
}
|
||||
#[inline]
|
||||
pub fn evaluated(val: T) -> Lazy<'a, T> {
|
||||
Lazy(UnsafeCell::new(Evaluated(val)))
|
||||
}
|
||||
#[inline]
|
||||
fn force<'b>(&'b self) { // not thread-safe
|
||||
unsafe {
|
||||
match *self.0.get() {
|
||||
Evaluated(_) => return, // nothing required; already Evaluated
|
||||
EvaluationInProgress =>
|
||||
panic!("Lazy::force called recursively!!!"),
|
||||
_ => () // need to do following something else if Unevaluated...
|
||||
} // following eliminates recursive race; drops neither on replace:
|
||||
match mem::replace(&mut *self.0.get(), EvaluationInProgress) {
|
||||
Unevaluated(thnk) => { // Thunk can't call force on same Lazy
|
||||
*self.0.get() = Evaluated(thnk.invoke());
|
||||
},
|
||||
_ => unreachable!() // already took care of other cases above.
|
||||
}
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn value<'b>(&'b self) -> &'b T {
|
||||
self.force(); // evaluatate if not evealutated
|
||||
match unsafe { &*self.0.get() } {
|
||||
&Evaluated(ref v) => v, // return value
|
||||
_ => { unreachable!() } // previous force guarantees Evaluated
|
||||
}
|
||||
}
|
||||
#[inline] // consumes the object to produce the value
|
||||
pub fn unwrap<'b>(self) -> T where T: 'b {
|
||||
self.force(); // evaluatate if not evealutated
|
||||
match { self.0.into_inner() } {
|
||||
Evaluated(v) => v,
|
||||
_ => unreachable!() // previous code guarantees Evaluated
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// now for immutable persistent shareable (memoized) LazyList via Lazy above...
|
||||
|
||||
type RcLazyListNode<'a, T> = Rc<Lazy<'a, LazyList<'a, T>>>;
|
||||
|
||||
use self::LazyList::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
enum LazyList<'a, T: 'a + Clone> {
|
||||
/// The Empty List
|
||||
Empty,
|
||||
/// A list with one member and possibly another list.
|
||||
Cons(T, RcLazyListNode<'a, T>)
|
||||
}
|
||||
|
||||
impl<'a, T: 'a + Clone> LazyList<'a, T> {
|
||||
#[inline]
|
||||
pub fn cons<F>(v: T, cntf: F) -> LazyList<'a, T>
|
||||
where F: 'a + FnOnce() -> LazyList<'a, T> {
|
||||
Cons(v, Rc::new(Lazy::new(cntf)))
|
||||
}
|
||||
#[inline]
|
||||
pub fn head<'b>(&'b self) -> &'b T {
|
||||
if let Cons(ref hd, _) = *self { return hd }
|
||||
panic!("LazyList::head called on an Empty LazyList!!!")
|
||||
}
|
||||
/* // not used
|
||||
#[inline]
|
||||
pub fn tail<'b>(&'b self) -> &'b Lazy<'a, LazyList<'a, T>> {
|
||||
if let Cons(_, ref rlln) = *self { return &*rlln }
|
||||
panic!("LazyList::tail called on an Empty LazyList!!!")
|
||||
}
|
||||
*/
|
||||
#[inline]
|
||||
pub fn unwrap(self) -> (T, RcLazyListNode<'a, T>) { // consumes the object
|
||||
if let Cons(hd, rlln) = self { return (hd, rlln) }
|
||||
panic!("LazyList::unwrap called on an Empty LazyList!!!")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: 'a + Clone> Iterator for LazyList<'a, T> {
|
||||
type Item = T;
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if let Empty = *self { return None }
|
||||
let oldll = mem::replace(self, Empty);
|
||||
let (hd, rlln) = oldll.unwrap();
|
||||
let mut newll = rlln.value().clone();
|
||||
// self now contains tail, newll contains the Empty
|
||||
mem::swap(self, &mut newll);
|
||||
Some(hd)
|
||||
}
|
||||
}
|
||||
|
||||
// implements worker wrapper recursion closures using shared RcMFn variable...
|
||||
|
||||
type RcMFn<'a, T> = Rc<UnsafeCell<Box<dyn FnMut(T) -> T + 'a>>>;
|
||||
|
||||
// #[derive(Clone)]
|
||||
// struct RcMFn<'a, T: 'a>(Rc<UnsafeCell<Box<FnMut() -> T + 'a>>>);
|
||||
|
||||
trait RcMFnMethods<'a, T> {
|
||||
fn create<F: FnMut(T) -> T + 'a>(v: F) -> RcMFn<'a, T>;
|
||||
fn invoke(&self, v: T) -> T;
|
||||
fn set<F: FnMut(T) -> T + 'a>(&self, v: F);
|
||||
}
|
||||
|
||||
impl<'a, T: 'a> RcMFnMethods<'a, T> for RcMFn<'a, T> {
|
||||
// creates new value wrapper...
|
||||
fn create<F: FnMut(T) -> T + 'a>(v: F) -> RcMFn<'a, T> {
|
||||
Rc::new(UnsafeCell::new(Box::new(v)))
|
||||
}
|
||||
#[inline(always)] // needs to be faster to be worth it
|
||||
fn invoke(&self, v: T) -> T {
|
||||
unsafe { (*(*(*self).get()))(v) }
|
||||
}
|
||||
fn set<F: FnMut(T) -> T + 'a>(&self, v: F) {
|
||||
unsafe { *self.get() = Box::new(v); }
|
||||
}
|
||||
}
|
||||
|
||||
type RcMVar<T> = Rc<RefCell<T>>;
|
||||
|
||||
trait RcMVarMethods<T> {
|
||||
fn create(v: T) -> Self;
|
||||
fn get(self: &Self) -> T;
|
||||
fn set(self: &Self, v: T);
|
||||
}
|
||||
|
||||
impl<T: Clone> RcMVarMethods<T> for RcMVar<T> {
|
||||
fn create(v: T) -> RcMVar<T> { // creates new value wrapped in RcMVar
|
||||
Rc::new(RefCell::new(v))
|
||||
}
|
||||
#[inline]
|
||||
fn get(&self) -> T {
|
||||
self.borrow().clone()
|
||||
}
|
||||
fn set(&self, v: T) {
|
||||
*self.borrow_mut() = v;
|
||||
}
|
||||
}
|
||||
|
||||
// finally what the task objective requires...
|
||||
|
||||
fn hammings() -> Box<dyn Iterator<Item = Rc<BigUint>>> {
|
||||
type LL<'a> = LazyList<'a, Rc<BigUint>>;
|
||||
fn merge<'a>(x: LL<'a>, y: LL<'a>) -> LL<'a> {
|
||||
let lte = { x.head() <= y.head() }; // private context for borrow
|
||||
if lte {
|
||||
let (hdx, tlx) = x.unwrap();
|
||||
LL::cons(hdx, move || merge(tlx.value().clone(), y))
|
||||
} else {
|
||||
let (hdy, tly) = y.unwrap();
|
||||
LL::cons(hdy, move || merge(x, tly.value().clone()))
|
||||
}
|
||||
}
|
||||
fn smult<'a>(m: BigUint, s: LL<'a>) -> LL<'a> { // like map m * but faster
|
||||
let smlt = RcMFn::create(move |ss: LL<'a>| ss);
|
||||
let csmlt = smlt.clone();
|
||||
smlt.set(move |ss: LL<'a>| {
|
||||
let (hd, tl) = ss.unwrap();
|
||||
let ccsmlt = csmlt.clone();
|
||||
LL::cons(Rc::new(&m * &*hd),
|
||||
move || ccsmlt.invoke(tl.value().clone()))
|
||||
});
|
||||
smlt.invoke(s)
|
||||
}
|
||||
fn u<'a>(s: LL<'a>, n: usize) -> LL<'a> {
|
||||
let nb = BigUint::from(n);
|
||||
let rslt = RcMVar::create(Empty);
|
||||
let crslt = rslt.clone(); // same interior data...
|
||||
let cll = LL::cons(Rc::new(BigUint::from(1u8)),
|
||||
move || crslt.get()); // gets future value
|
||||
// below sets future value for above closure...
|
||||
rslt.set(if let Empty =
|
||||
s { smult(nb, cll) } else { merge(s, smult(nb, cll)) });
|
||||
rslt.get()
|
||||
}
|
||||
fn rll<'a>() -> LL<'a> { [5, 3, 2].iter()
|
||||
.fold(Empty, |ll, n| u(ll, *n) ) }
|
||||
let hmng = LL::cons(Rc::new(BigUint::from(1u8)), move || rll());
|
||||
Box::new(hmng.into_iter())
|
||||
}
|
||||
|
||||
// and the required test outputs...
|
||||
|
||||
fn main() {
|
||||
print!("[");
|
||||
for (i, h) in hammings().take(20).enumerate() {
|
||||
if i != 0 { print!(",") }
|
||||
print!(" {}", h)
|
||||
}
|
||||
println!(" ]");
|
||||
|
||||
println!("{}", hammings().take(1691).last().unwrap());
|
||||
|
||||
let strt = Instant::now();
|
||||
|
||||
let rslt = hammings().take(1000000).last().unwrap();
|
||||
|
||||
let elpsd = strt.elapsed();
|
||||
let secs = elpsd.as_secs();
|
||||
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
|
||||
let dur = secs * 1000 + millis;
|
||||
|
||||
println!("{}", rslt);
|
||||
|
||||
println!("This last took {} milliseconds.", dur);
|
||||
}
|
||||
297
Task/Hamming-numbers/Rust/hamming-numbers-6.rust
Normal file
297
Task/Hamming-numbers/Rust/hamming-numbers-6.rust
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
extern crate num;
|
||||
use num::bigint::BigUint;
|
||||
|
||||
use core::cmp::Ordering;
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::cell::{UnsafeCell, RefCell};
|
||||
use std::mem;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
// implementation of Thunk closure here...
|
||||
|
||||
pub struct Thunk<'a, R>(Box<dyn FnOnce() -> R + 'a>);
|
||||
|
||||
impl<'a, R: 'a> Thunk<'a, R> {
|
||||
#[inline(always)]
|
||||
fn new<F: 'a + FnOnce() -> R>(func: F) -> Thunk<'a, R> {
|
||||
Thunk(Box::new(func))
|
||||
}
|
||||
#[inline(always)]
|
||||
fn invoke(self) -> R { self.0() }
|
||||
}
|
||||
|
||||
// actual Lazy implementation starts here...
|
||||
|
||||
use self::LazyState::*;
|
||||
|
||||
pub struct Lazy<'a, T: 'a>(UnsafeCell<LazyState<'a, T>>);
|
||||
|
||||
enum LazyState<'a, T: 'a> {
|
||||
Unevaluated(Thunk<'a, T>),
|
||||
EvaluationInProgress,
|
||||
Evaluated(T)
|
||||
}
|
||||
|
||||
impl<'a, T: 'a> Lazy<'a, T>{
|
||||
#[inline]
|
||||
pub fn new<'b, F>(thunk: F) -> Lazy<'b, T>
|
||||
where F: 'b + FnOnce() -> T {
|
||||
Lazy(UnsafeCell::new(Unevaluated(Thunk::new(thunk))))
|
||||
}
|
||||
#[inline]
|
||||
pub fn evaluated(val: T) -> Lazy<'a, T> {
|
||||
Lazy(UnsafeCell::new(Evaluated(val)))
|
||||
}
|
||||
#[inline]
|
||||
fn force<'b>(&'b self) { // not thread-safe
|
||||
unsafe {
|
||||
match *self.0.get() {
|
||||
Evaluated(_) => return, // nothing required; already Evaluated
|
||||
EvaluationInProgress =>
|
||||
panic!("Lazy::force called recursively!!!"),
|
||||
_ => () // need to do following something else if Unevaluated...
|
||||
} // following eliminates recursive race; drops neither on replace:
|
||||
match mem::replace(&mut *self.0.get(), EvaluationInProgress) {
|
||||
Unevaluated(thnk) => { // Thunk can't call force on same Lazy
|
||||
*self.0.get() = Evaluated(thnk.invoke());
|
||||
},
|
||||
_ => unreachable!() // already took care of other cases above.
|
||||
}
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn value<'b>(&'b self) -> &'b T {
|
||||
self.force(); // evaluatate if not evealutated
|
||||
match unsafe { &*self.0.get() } {
|
||||
&Evaluated(ref v) => v, // return value
|
||||
_ => { unreachable!() } // previous force guarantees Evaluated
|
||||
}
|
||||
}
|
||||
#[inline] // consumes the object to produce the value
|
||||
pub fn unwrap<'b>(self) -> T where T: 'b {
|
||||
self.force(); // evaluatate if not evealutated
|
||||
match { self.0.into_inner() } {
|
||||
Evaluated(v) => v,
|
||||
_ => unreachable!() // previous code guarantees Evaluated
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// now for immutable persistent shareable (memoized) LazyList via Lazy above...
|
||||
|
||||
type RcLazyListNode<'a, T> = Rc<Lazy<'a, LazyList<'a, T>>>;
|
||||
|
||||
use self::LazyList::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
enum LazyList<'a, T: 'a + Clone> {
|
||||
/// The Empty List
|
||||
Empty,
|
||||
/// A list with one member and possibly another list.
|
||||
Cons(T, RcLazyListNode<'a, T>)
|
||||
}
|
||||
|
||||
impl<'a, T: 'a + Clone> LazyList<'a, T> {
|
||||
#[inline]
|
||||
pub fn cons<F>(v: T, cntf: F) -> LazyList<'a, T>
|
||||
where F: 'a + FnOnce() -> LazyList<'a, T> {
|
||||
Cons(v, Rc::new(Lazy::new(cntf)))
|
||||
}
|
||||
#[inline]
|
||||
pub fn head<'b>(&'b self) -> &'b T {
|
||||
if let Cons(ref hd, _) = *self { return hd }
|
||||
panic!("LazyList::head called on an Empty LazyList!!!")
|
||||
}
|
||||
#[inline]
|
||||
pub fn unwrap(self) -> (T, RcLazyListNode<'a, T>) { // consumes the object
|
||||
if let Cons(hd, rlln) = self { return (hd, rlln) }
|
||||
panic!("LazyList::unwrap called on an Empty LazyList!!!")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: 'a + Clone> Iterator for LazyList<'a, T> {
|
||||
type Item = T;
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if let Empty = *self { return None }
|
||||
let oldll = mem::replace(self, Empty);
|
||||
let (hd, rlln) = oldll.unwrap();
|
||||
let mut newll = rlln.value().clone();
|
||||
// self now contains tail, newll contains the Empty
|
||||
mem::swap(self, &mut newll);
|
||||
Some(hd)
|
||||
}
|
||||
}
|
||||
|
||||
// implements worker wrapper recursion closures using shared RcMFn variable...
|
||||
|
||||
type RcMFn<'a, T> = Rc<UnsafeCell<Box<dyn FnMut(T) -> T + 'a>>>;
|
||||
|
||||
trait RcMFnMethods<'a, T> {
|
||||
fn create<F: FnMut(T) -> T + 'a>(v: F) -> RcMFn<'a, T>;
|
||||
fn invoke(&self, v: T) -> T;
|
||||
fn set<F: FnMut(T) -> T + 'a>(&self, v: F);
|
||||
}
|
||||
|
||||
impl<'a, T: 'a> RcMFnMethods<'a, T> for RcMFn<'a, T> {
|
||||
// creates new value wrapper...
|
||||
fn create<F: FnMut(T) -> T + 'a>(v: F) -> RcMFn<'a, T> {
|
||||
Rc::new(UnsafeCell::new(Box::new(v)))
|
||||
}
|
||||
#[inline(always)] // needs to be faster to be worth it
|
||||
fn invoke(&self, v: T) -> T {
|
||||
unsafe { (*(*(*self).get()))(v) }
|
||||
}
|
||||
fn set<F: FnMut(T) -> T + 'a>(&self, v: F) {
|
||||
unsafe { *self.get() = Box::new(v); }
|
||||
}
|
||||
}
|
||||
|
||||
type RcMVar<T> = Rc<RefCell<T>>;
|
||||
|
||||
trait RcMVarMethods<T> {
|
||||
fn create(v: T) -> Self;
|
||||
fn get(self: &Self) -> T;
|
||||
fn set(self: &Self, v: T);
|
||||
}
|
||||
|
||||
impl<T: Clone> RcMVarMethods<T> for RcMVar<T> {
|
||||
fn create(v: T) -> RcMVar<T> { // creates new value wrapped in RcMVar
|
||||
Rc::new(RefCell::new(v))
|
||||
}
|
||||
#[inline]
|
||||
fn get(&self) -> T {
|
||||
self.borrow().clone()
|
||||
}
|
||||
fn set(&self, v: T) {
|
||||
*self.borrow_mut() = v;
|
||||
}
|
||||
}
|
||||
|
||||
// finally what the task objective requires...
|
||||
|
||||
#[derive(Clone)]
|
||||
struct LogRep {lg: f64, x2: u32, x3: u32, x5: u32}
|
||||
|
||||
const ONE: LogRep = LogRep { lg: 0f64, x2: 0u32, x3: 0u32, x5: 0u32 };
|
||||
const LB3: f64 = 1.5849625007211563f64; // log base two of 3f64
|
||||
const LB5: f64 = 2.321928094887362f64; // log base two of 5f64
|
||||
|
||||
impl PartialEq for LogRep {
|
||||
#[inline]
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.lg == other.lg
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for LogRep {}
|
||||
|
||||
impl PartialOrd for LogRep {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
self.lg.partial_cmp(&other.lg)
|
||||
}
|
||||
}
|
||||
|
||||
trait LogRepMults {
|
||||
fn mult2(lr: LogRep) -> LogRep;
|
||||
fn mult3(lr: LogRep) -> LogRep;
|
||||
fn mult5(lr: LogRep) -> LogRep;
|
||||
}
|
||||
|
||||
impl LogRepMults for LogRep {
|
||||
#[inline]
|
||||
fn mult2(lr: LogRep) -> LogRep {
|
||||
LogRep { lg: lr.lg + 1f64, x2: lr.x2 + 1, x3: lr.x3, x5: lr.x5 }
|
||||
}
|
||||
#[inline]
|
||||
fn mult3(lr: LogRep) -> LogRep {
|
||||
LogRep { lg: lr.lg + LB3, x2: lr.x2, x3: lr.x3 + 1, x5: lr.x5 }
|
||||
}
|
||||
#[inline]
|
||||
fn mult5(lr: LogRep) -> LogRep {
|
||||
LogRep { lg: lr.lg + LB5, x2: lr.x2, x3: lr.x3, x5: lr.x5 + 1 }
|
||||
}
|
||||
}
|
||||
|
||||
fn logrep2biguint(lr: LogRep) -> BigUint {
|
||||
let two = BigUint::from(2u8);
|
||||
let three = BigUint::from(3u8);
|
||||
let five = BigUint::from(5u8);
|
||||
fn xpnd(vm: u32, n: BigUint) -> BigUint {
|
||||
let mut rslt = BigUint::from(1u8);
|
||||
let mut v = vm; let mut bsm = n;
|
||||
while v > 0u32 {
|
||||
if v & 1u32 != 0u32 { rslt = rslt * &bsm }
|
||||
bsm = &bsm.clone() * bsm; v = v >> 1;
|
||||
}
|
||||
rslt
|
||||
}
|
||||
xpnd(lr.x2, two) * xpnd(lr.x3, three) * xpnd(lr.x5, five)
|
||||
}
|
||||
|
||||
fn hammings() -> Box<dyn Iterator<Item = LogRep>> {
|
||||
type LR = LogRep;
|
||||
type LL<'a> = LazyList<'a, LR>;
|
||||
fn merge<'a>(x: LL<'a>, y: LL<'a>) -> LL<'a> {
|
||||
let lte = { x.head() <= y.head() }; // private context for borrow
|
||||
if lte {
|
||||
let (hdx, tlx) = x.unwrap();
|
||||
LL::cons(hdx, move || merge(tlx.value().clone(), y))
|
||||
} else {
|
||||
let (hdy, tly) = y.unwrap();
|
||||
LL::cons(hdy, move || merge(x, tly.value().clone()))
|
||||
}
|
||||
}
|
||||
fn smult<'a>(m: fn(LogRep) -> LogRep, s: LL<'a>) -> LL<'a> { // like map m * but faster
|
||||
let smlt = RcMFn::create(move |ss: LL<'a>| ss);
|
||||
let csmlt = smlt.clone();
|
||||
smlt.set(move |ss: LL<'a>| {
|
||||
let (hd, tl) = ss.unwrap();
|
||||
let ccsmlt = csmlt.clone();
|
||||
LL::cons(m(hd), move || ccsmlt.invoke(tl.value().clone()))
|
||||
});
|
||||
smlt.invoke(s)
|
||||
}
|
||||
fn u<'a>(s: LL<'a>, f: fn(LogRep) -> LogRep) -> LL<'a> {
|
||||
let rslt = RcMVar::create(Empty);
|
||||
let crslt = rslt.clone(); // same interior data...
|
||||
let cll = LL::cons(ONE, move || crslt.get()); // gets future value
|
||||
// below sets future value for above closure...
|
||||
rslt.set(if let Empty =
|
||||
s { smult(f, cll) } else { merge(s, smult(f, cll)) });
|
||||
rslt.get()
|
||||
}
|
||||
fn rll<'a>() -> LL<'a> { [LR::mult5, LR::mult3, LR::mult2].iter()
|
||||
.fold(Empty, |ll, mf| u(ll, *mf) ) }
|
||||
let hmng = LL::cons(ONE, move || rll());
|
||||
Box::new(hmng.into_iter())
|
||||
}
|
||||
|
||||
// and the required test outputs...
|
||||
|
||||
fn main() {
|
||||
print!("[");
|
||||
for (i, h) in hammings().take(20).enumerate() {
|
||||
if i != 0 { print!(",") }
|
||||
print!(" {}", logrep2biguint(h))
|
||||
}
|
||||
println!(" ]");
|
||||
|
||||
println!("{}", logrep2biguint(hammings().take(1691).last().unwrap()));
|
||||
|
||||
let strt = Instant::now();
|
||||
|
||||
let rslt = hammings().take(1000000).last().unwrap();
|
||||
|
||||
let elpsd = strt.elapsed();
|
||||
let secs = elpsd.as_secs();
|
||||
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
|
||||
let dur = secs * 1000 + millis;
|
||||
|
||||
println!("{}", logrep2biguint(rslt));
|
||||
|
||||
println!("This last took {} milliseconds.", dur);
|
||||
}
|
||||
145
Task/Hamming-numbers/Rust/hamming-numbers-7.rust
Normal file
145
Task/Hamming-numbers/Rust/hamming-numbers-7.rust
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
extern crate num;
|
||||
use num::bigint::BigInt;
|
||||
|
||||
use core::fmt::Display;
|
||||
use std::time::Instant;
|
||||
use std::iter;
|
||||
|
||||
const NUM_ELEMENTS: usize = 1000000;
|
||||
|
||||
const LB2_2: f64 = 1.0_f64; // log2(2.0)
|
||||
const LB2_3: f64 = 1.5849625007211563_f64; // log2(3.0)
|
||||
const LB2_5: f64 = 2.321928094887362_f64; // log2(5.0)
|
||||
|
||||
#[derive (Clone)]
|
||||
struct LogRep {
|
||||
lr: f64,
|
||||
x2: u32,
|
||||
x3: u32,
|
||||
x5: u32,
|
||||
}
|
||||
impl LogRep {
|
||||
fn int_value(&self) -> BigInt {
|
||||
BigInt::from(2).pow(self.x2) * BigInt::from(3).pow(self.x3) * BigInt::from(5).pow(self.x5)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn mul2(&self) -> Self {
|
||||
LogRep {
|
||||
lr: self.lr + LB2_2,
|
||||
x2: self.x2 + 1,
|
||||
x3: self.x3,
|
||||
x5: self.x5,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn mul3(&self) -> Self {
|
||||
LogRep {
|
||||
lr: self.lr + LB2_3,
|
||||
x2: self.x2,
|
||||
x3: self.x3 + 1,
|
||||
x5: self.x5,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn mul5(&self) -> Self {
|
||||
LogRep {
|
||||
lr: self.lr + LB2_5,
|
||||
x2: self.x2,
|
||||
x3: self.x3,
|
||||
x5: self.x5 + 1,
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Display for LogRep {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let val = self.int_value();
|
||||
let x2 = self.x2;
|
||||
let x3 = self.x3;
|
||||
let x5 = self.x5;
|
||||
write!(f, "[{x2} {x3} {x5}]=>{val}")
|
||||
}
|
||||
}
|
||||
|
||||
const ONE: LogRep = LogRep { lr: 0.0, x2: 0, x3: 0, x5: 0 };
|
||||
struct LogRepImperativeIterator {
|
||||
s2: Vec<LogRep>,
|
||||
s3: Vec<LogRep>,
|
||||
s5: LogRep,
|
||||
mrg: LogRep,
|
||||
s2i: usize,
|
||||
s3i: usize,
|
||||
}
|
||||
impl LogRepImperativeIterator {
|
||||
pub fn new() -> Self {
|
||||
LogRepImperativeIterator {
|
||||
s2: vec![ONE.mul2()],
|
||||
s3: vec![ONE.mul3()],
|
||||
s5: ONE.mul5(),
|
||||
mrg: ONE.mul3(),
|
||||
s2i: 0,
|
||||
s3i: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn iter(&self) -> impl Iterator<Item = LogRep> {
|
||||
iter::once(ONE).chain(LogRepImperativeIterator::new())
|
||||
}
|
||||
}
|
||||
impl Iterator for LogRepImperativeIterator {
|
||||
type Item = LogRep;
|
||||
|
||||
#[inline(always)]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.s2i + self.s2i >= self.s2.len() {
|
||||
self.s2.drain(0..self.s2i);
|
||||
self.s2i = 0;
|
||||
}
|
||||
let result: LogRep;
|
||||
if self.s2[self.s2i].lr < self.mrg.lr {
|
||||
self.s2.push(self.s2[self.s2i].mul2());
|
||||
result = self.s2[self.s2i].clone(); self.s2i += 1;
|
||||
} else {
|
||||
if self.s3i + self.s3i >= self.s3.len() {
|
||||
self.s3.drain(0..self.s3i);
|
||||
self.s3i = 0;
|
||||
}
|
||||
|
||||
result = self.mrg.clone();
|
||||
self.s2.push(self.mrg.mul2());
|
||||
self.s3.push(self.mrg.mul3());
|
||||
|
||||
self.s3i += 1;
|
||||
if self.s3[self.s3i].lr < self.s5.lr {
|
||||
self.mrg = self.s3[self.s3i].clone();
|
||||
} else {
|
||||
self.mrg = self.s5.clone();
|
||||
self.s5 = self.s5.mul5();
|
||||
self.s3i -= 1;
|
||||
}
|
||||
};
|
||||
|
||||
Some(result)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
LogRepImperativeIterator::new().iter().take(20)
|
||||
.for_each(&|h: LogRep| print!("{} ", h.int_value()));
|
||||
println!();
|
||||
|
||||
println!("{} ", LogRepImperativeIterator::new().iter()
|
||||
.take(1691).last().unwrap().int_value());
|
||||
|
||||
let t0 = Instant::now();
|
||||
let rslt = LogRepImperativeIterator::new().iter()
|
||||
.take(NUM_ELEMENTS).last().unwrap();
|
||||
let elpsd = t0.elapsed().as_micros() as f64;
|
||||
|
||||
println!("{}", rslt.int_value());
|
||||
println!("This took {} microseconds for {} elements!", elpsd, NUM_ELEMENTS)
|
||||
}
|
||||
95
Task/Hamming-numbers/Rust/hamming-numbers-8.rust
Normal file
95
Task/Hamming-numbers/Rust/hamming-numbers-8.rust
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
extern crate num; // requires dependency on the num library
|
||||
use num::bigint::BigUint;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
fn nth_hamming(n: u64) -> (u32, u32, u32) {
|
||||
if n < 2 {
|
||||
if n <= 0 { panic!("nth_hamming: argument is zero; no elements") }
|
||||
return (0, 0, 0) // trivial case for n == 1
|
||||
}
|
||||
|
||||
let lg3 = 3.0f64.ln() / 2.0f64.ln(); // log base 2 of 3
|
||||
let lg5 = 5.0f64.ln() / 2.0f64.ln(); // log base 2 of 5
|
||||
let fctr = 6.0f64 * lg3 * lg5;
|
||||
let crctn = 30.0f64.sqrt().ln() / 2.0f64.ln(); // log base 2 of sqrt 30
|
||||
let lgest = (fctr * n as f64).powf(1.0f64/3.0f64)
|
||||
- crctn; // from WP formula
|
||||
let frctn = if n < 1000000000 { 0.509f64 } else { 0.105f64 };
|
||||
let lghi = (fctr * (n as f64 + frctn * lgest)).powf(1.0f64/3.0f64)
|
||||
- crctn; // calculate hi log limit based on log(N) - WP article
|
||||
let lglo = 2.0f64 * lgest - lghi; // and a lower limit of the upper "band"
|
||||
let mut count = 0; // need to use extended precision, might go over
|
||||
let mut bnd = Vec::with_capacity(0);
|
||||
let klmt = (lghi / lg5) as u32 + 1;
|
||||
for k in 0 .. klmt { // i, j, k values can be just u32 values
|
||||
let p = k as f64 * lg5;
|
||||
let jlmt = ((lghi - p) / lg3) as u32 + 1;
|
||||
for j in 0 .. jlmt {
|
||||
let q = p + j as f64 * lg3;
|
||||
let ir = lghi - q;
|
||||
let lg = q + (ir as u32) as f64; // current log value (estimated)
|
||||
count += ir as u64 + 1;
|
||||
if lg >= lglo {
|
||||
bnd.push((lg, (ir as u32, j, k)))
|
||||
}
|
||||
}
|
||||
}
|
||||
if n > count { panic!("nth_hamming: band high estimate is too low!") };
|
||||
let ndx = (count - n) as usize;
|
||||
if ndx >= bnd.len() { panic!("nth_hamming: band low estimate is too high!") };
|
||||
bnd.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap()); // sort decreasing order
|
||||
|
||||
bnd[ndx].1
|
||||
}
|
||||
|
||||
fn convert_log2big(o: (u32, u32, u32)) -> BigUint {
|
||||
let two = BigUint::from(2u8);
|
||||
let three = BigUint::from(3u8);
|
||||
let five = BigUint::from(5u8);
|
||||
let (x2, x3, x5) = o;
|
||||
let mut ob = BigUint::from(1u8); // convert to BigUint at the end
|
||||
for _ in 0 .. x2 { ob = ob * &two }
|
||||
for _ in 0 .. x3 { ob = ob * &three }
|
||||
for _ in 0 .. x5 { ob = ob * &five }
|
||||
ob
|
||||
}
|
||||
|
||||
fn main() {
|
||||
print!("[");
|
||||
for (i, h) in (1 .. 21).map(nth_hamming).enumerate() {
|
||||
if i != 0 { print!(",") }
|
||||
print!(" {}", convert_log2big(h))
|
||||
}
|
||||
println!(" ]");
|
||||
println!("{}", convert_log2big(nth_hamming(1691)));
|
||||
|
||||
let strt = Instant::now();
|
||||
|
||||
let rslt = nth_hamming(1000000);
|
||||
|
||||
let elpsd = strt.elapsed();
|
||||
let secs = elpsd.as_secs();
|
||||
let millis = (elpsd.subsec_nanos() / 1000000)as u64;
|
||||
let dur = secs * 1000 + millis;
|
||||
|
||||
println!("2^{} times 3^{} times 5^{}", rslt.0, rslt.1, rslt.2);
|
||||
let rs = convert_log2big(rslt).to_str_radix(10);
|
||||
let mut s = rs.as_str();
|
||||
println!("{} digits:", s.len());
|
||||
let lg3 = 3.0f64.log2();
|
||||
let lg5 = 5.0f64.log2();
|
||||
let lg = (rslt.0 as f64 + rslt.1 as f64 * lg3
|
||||
+ rslt.2 as f64 * lg5) * 2.0f64.log10();
|
||||
println!("Approximately {}E+{}", 10.0f64.powf(lg.fract()), lg.trunc());
|
||||
if s.len() <= 10000 {
|
||||
while s.len() > 100 {
|
||||
let (f, r) = s.split_at(100);
|
||||
s = r;
|
||||
println!("{}", f);
|
||||
}
|
||||
println!("{}", s);
|
||||
}
|
||||
|
||||
println!("This last took {} milliseconds.", dur);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue