// Copyright (C) 2014 by Alexandru Cojocaru // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see . fn todigs(n: u32) -> Vec { let mut m = n; let mut ds = vec![]; while m != 0 { ds.push ((m%10) as u8); m /= 10; } ds } fn fromdigs(v: &Vec) -> u32 { let mut n = 0; for d in v.iter () { n *= 10; n += *d as u32; } n } fn kaprekar(n: u32) -> u32 { let mut ds = todigs(n); ds.sort_by (|a,b| a.cmp(b).reverse()); let n1 = fromdigs(&ds); ds.reverse (); let n2 = fromdigs(&ds); n1 - n2 } fn brent(f: F, x0: u32) -> (u32,u32) where F: Fn(u32) -> u32 { let mut pow = 1; let mut lam = 1; let mut tort = x0; let mut hare = f(x0); while tort != hare { if pow == lam { tort = hare; pow *= 2; lam = 0; } hare = f(hare); lam += 1; } let mut mu = 0; tort = x0; hare = x0; for _ in 0..lam { hare = f(hare); } while tort != hare { tort = f(tort); hare = f(hare); mu += 1; } (mu,lam) } fn main() { let b = brent(kaprekar, 61974); println!("{}, {}", b.0, b.1); }