Last active
March 31, 2024 16:37
-
-
Save nanpuyue/e1934ace1f900b5a961982899b4b8e15 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// date: 2020-01-10 | |
// update: 2024-04-01 | |
// license: GPLv3 https://www.gnu.org/licenses/gpl-3.0.txt | |
// author: nanpuyue <[email protected]> https://blog.nanpuyue.com | |
#![feature(coroutines)] | |
#![feature(coroutine_trait)] | |
use std::ops::{Coroutine, CoroutineState}; | |
use std::pin::Pin; | |
fn prime_generator() -> impl Coroutine<Yield = u16, Return = Vec<u16>> { | |
|| { | |
yield 2; | |
yield 3; | |
let mut n = 3u16; | |
let mut l = vec![n]; | |
while let Some(x) = n.checked_add(2) { | |
n = x; | |
let mut y = true; | |
for &i in &l { | |
let (q, r) = (n / i, n % i); | |
if i > q { | |
break; | |
} else if r == 0 { | |
y = false; | |
break; | |
} | |
} | |
if y { | |
l.push(n); | |
yield n; | |
} | |
} | |
l | |
} | |
} | |
fn main() { | |
let mut coroutine = prime_generator(); | |
let mut i = 0; | |
print!("\n 0: "); | |
loop { | |
match Pin::new(&mut coroutine).resume(()) { | |
CoroutineState::Yielded(x) => { | |
print!("{x:5} "); | |
if i % 10 == 9 { | |
print!("\n{:4}: ", i + 1); | |
} | |
i += 1; | |
} | |
CoroutineState::Complete(v) => { | |
println!("\n\ntotal: {}", v.len() + 1); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.rust-lang.org/?version=nightly&mode=release&edition=2024&gist=e1934ace1f900b5a961982899b4b8e15