# 用欧拉计划学习Rust编程(第13~16题）

## 第13题 大整数求和

[dependencies]
num-bigint = "0.2.2"


extern crate num_bigint;
use num_bigint::BigUint;


100个大整数这里用字符串数组表示。

let numbers = [
"37107287533902102798797998220837590246510135740250",
"46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629",
"22918802058777319719839450180888072429661980811197",
// 省略了很多行
"77158542502016545090413245809786882778948721859617",
"72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722",
"53503534226472524250874054075591789781264330331690",
];



let mut sum = BigUint::from(0 as u64);
for s in numbers.iter() {
sum += BigUint::parse_bytes(s.as_bytes(), 10).unwrap();
}
let full_str = sum.to_string();
println!("take 10 digits: {}", &full_str[..10]);


## 第14题

Collatz序列的意思是，当一个数n是偶数时，下一数为n/2；当n为奇数时，下一个数为3*n+1。

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

fn collatz_len(x: u64) -> u64 {
if x == 1 {
return 1;
}
let y;
if x % 2 == 0 {
y = x / 2;
} else {
y = x * 3 + 1;
}
collatz_len(y) + 1
}


fn collatz_len(x: u64) -> u64 {
if x == 1 {
return 1;
}
let y = if x % 2 == 0 { x / 2 } else { x * 3 + 1 };
collatz_len(y) + 1
}


fn main() {
let mut max = 0;
for num in 1..1_000_000 {
let c = collatz_len(num as u64);
if c > max {
max = c;
println!("start num: {}   chain length: {}", num, max);
}
}
}


## 第15题

P(m,n) = P(m-1,n) + P(m-1,n-1) + ... + P(m-1,1) + P(m-1,0)

fn path_slow(m: usize, n: usize) -> u64 {
if m == 0 || n == 0 { return 1; }
let mut sum = 0;
for j in 0..=n {
sum += path_slow(m-1, j);
}
return sum;
}

fn main() {
println!("{}", path_slow(12, 12));
println!("{}", path_slow(20, 20));
}


fn main() {
let mut v: Vec<u64> = vec![0; 10000];
println!("{}", path_fast(&mut v, 20, 20));
}

fn path_fast(v: &mut Vec<u64>, m: usize, n: usize) -> u64 {
if m == 0 || n == 0 {
return 1;
}
if v[m * 100 + n] > 0 {
return v[m * 100 + n];
} //缓存命中
let mut sum = 0;
for j in 0..=n {
sum += path_fast(v, m - 1, j);
}
v[m * 100 + n] = sum; // 加入缓存中
println!("({},{}) {}", m, n, sum);
return sum;
}


## 第16题

extern crate num_bigint;
use num_bigint::BigUint;


let mut prod = BigUint::from(1 as u64);
for _i in 0..1000 {
prod *= BigUint::from(2 as u64);
}
let full_str = prod.to_string();
println!("{}", full_str);


let pow2_1000 = (0..1000).fold(BigUint::from(1 as u64), |p, _a| p*BigUint::from(2 as u64));
println!("{}", pow2_1000);


let s = full_str
.chars()
.map(|c| c.to_digit(10).unwrap())
.sum::<u32>();
println!("{}", s);


1539870_KBNiIXymh4SnmDEDZmUTg7tu1MTBVlLj

----==== Email: slofslb (GTD) qq.com 请将(GTD)换成@ ====----

---- 魔方桥牌象棋、游戏人生...