Skip to content

Instantly share code, notes, and snippets.

@nanpuyue
Last active March 31, 2024 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanpuyue/e1934ace1f900b5a961982899b4b8e15 to your computer and use it in GitHub Desktop.
Save nanpuyue/e1934ace1f900b5a961982899b4b8e15 to your computer and use it in GitHub Desktop.
// date: 2020-01-10
// update: 2024-04-01
// license: GPLv3 https://www.gnu.org/licenses/gpl-3.0.txt
// author: nanpuyue <nanpuyue@gmail.com> 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