|
| 1 | +pub struct Solution; |
| 2 | + |
| 3 | +// ------------------------------------------------------ snip ------------------------------------------------------ // |
| 4 | + |
| 5 | +impl Solution { |
| 6 | + pub fn prime_sub_operation(nums: Vec<i32>) -> bool { |
| 7 | + const PRIMES: [u16; 168] = [ |
| 8 | + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, |
| 9 | + 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, |
| 10 | + 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, |
| 11 | + 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, |
| 12 | + 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, |
| 13 | + 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, |
| 14 | + 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, |
| 15 | + 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, |
| 16 | + ]; |
| 17 | + |
| 18 | + let mut prev = 0; |
| 19 | + |
| 20 | + nums.iter().all(|&num| { |
| 21 | + let num = num as u16; |
| 22 | + |
| 23 | + if num <= prev { |
| 24 | + return false; |
| 25 | + } |
| 26 | + |
| 27 | + let upper_bound = num - prev; |
| 28 | + let index = PRIMES.partition_point(|&x| x < upper_bound); |
| 29 | + |
| 30 | + prev = num - PRIMES.get(index.wrapping_sub(1)).copied().unwrap_or(0); |
| 31 | + |
| 32 | + true |
| 33 | + }) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// ------------------------------------------------------ snip ------------------------------------------------------ // |
| 38 | + |
| 39 | +impl super::Solution for Solution { |
| 40 | + fn prime_sub_operation(nums: Vec<i32>) -> bool { |
| 41 | + Self::prime_sub_operation(nums) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +#[cfg(test)] |
| 46 | +mod tests { |
| 47 | + #[test] |
| 48 | + fn test_solution() { |
| 49 | + super::super::tests::run::<super::Solution>(); |
| 50 | + } |
| 51 | +} |
0 commit comments