Rust: codewars的primes-in-numbers
来源:互联网 发布:帝国cms标签大全 编辑:程序博客网 时间:2024/06/01 07:38
在codewars中,有一个质因数分解题:
https://www.codewars.com/kata/primes-in-numbers/train/rust
比如,有一个数,86240,我们可以分解如下:
86240=2 x 2 x 2 x 2 x 2 x 5 x 7 x 7 x 11
请写一个输出如此格式:(2**5)(5)(7**2)(11)。
一、我的代码
fn prime_factors(n: i64) -> String { // your code if is_prime(n){return format_print(vec![n]);} let mut m = n; let mut output: Vec<i64> = Vec::new(); for i in 2..n + 1 { if !is_prime(i) { continue; } while m % i == 0i64 { output.push(i); m = m / i; } if m < i { break; } } println!("output:{:?}", output); format_print(output)}fn is_prime(n: i64) -> bool { match n<=1{ true =>return false, _=>return !(2..n).any(|x| n % x == 0), }}fn format_print(v: Vec<i64>) -> String { let len = v.len(); let mut strs = "".to_string(); let mut repeat_n = 1; for i in 0..len { if i != 0 { if &v[i] == &v[i - 1] { repeat_n += 1; } else { match repeat_n { 1 => strs.push_str(&format!("({})", &v[i - 1])), _ => strs.push_str(&format!("({}**{})", &v[i - 1], repeat_n)), }; repeat_n = 1; if i == len - 1 { strs.push_str(&format!("({})", &v[i])); } } } } strs}
调试运行:
fn main() { let st = SystemTime::now(); println!("7919=>{}", prime_factors(7919)); println!("1=>{}", prime_factors(862400)); println!("2=>{}", prime_factors(7775460)); println!("3=>{}", prime_factors(17 * 17 * 93 * 677)); let mt1 = SystemTime::now(); println!("is_fit_num time:{:?}", mt1.duration_since(st).unwrap()); thread::sleep_ms(500000);}
结果输出以及用时:
7919=>(7919)output:[2, 2, 2, 2, 2, 2, 5, 5, 7, 7, 11]1=>(2**6)(5**2)(7**2)(11)output:[2, 2, 3, 3, 3, 5, 7, 11, 11, 17]2=>(2**2)(3**3)(5)(7)(11**2)(17)output:[3, 17, 17, 31, 677]3=>(3)(17**2)(31)(677)is_fit_num time:Duration { secs: 0, nanos: 1003300 }
通过了相关测试,但由于codewars认为用时过长(要求在12秒以内运行结束),无法接受codewars的提交。接下来还需优化。
原因是,弄个大数,上面的程序就会挂(用时过长),比如:
println!("987654321 =>{}", prime_factors(987654321));//估计要40秒
二、其他精彩的解法
这个需等我过关了,才能知道…….
阅读全文
0 0
- Rust: codewars的primes-in-numbers
- Rust : codewars的Product of consecutive Fib numbers
- Rust: codewars 的Duplicate Encoder
- Rust: codewars的Bleatrix Trotter
- Rust: codewars的prize draw算法
- Rust : codewars的up AND down 算法
- Rust : codewars的Sum of Pairs
- Rust: codewars的Roman Numerals Encoder
- Rust: codewars的Sum by Factors
- Rust: codewars的DNA to RNA Conversion
- Rust: codewars的Highest and Lowest
- Rust: codewars的Molecule to atoms
- Rust: codewars 的Count of positives / sum of negatives
- Rust: codewars的Simple Substitution Cipher Helper算法题、N种不简单的解法集
- CodeWars:Sum of odd numbers
- [Haskell] CodeWars|Sum of odd numbers
- PRIMES is in P
- (转)Rust: Rust的 Deref 运算符
- 大型高并发高负载网站的系统架构
- c++ 在编译期折腾的一些方法
- java操作excel
- K:java中的内存泄露
- Java SE8 Lambda 基础入门---forEach
- Rust: codewars的primes-in-numbers
- switch case用法
- http详解(1)(转)
- 用JabRef生成Latex参考文献
- Spring Boot开发Web项目
- 网络配置
- 常见的八种导致 APP 内存泄漏的问题(下)
- 类中不写成员函数易犯错误
- 软件架构师应该具备的素质