Skip to content

Instantly share code, notes, and snippets.

@potatosalad
Created June 11, 2019 20:25
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 potatosalad/cee5e920d0e8954db345d02e6e1cb305 to your computer and use it in GitHub Desktop.
Save potatosalad/cee5e920d0e8954db345d02e6e1cb305 to your computer and use it in GitHub Desktop.
[package]
name = "nth-prime"
version = "0.1.0"
edition = "2018"
[dependencies]
futures-preview = "0.3.0-alpha.16"
#![feature(async_await, await_macro)]
extern crate futures;
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
fn is_prime(x: u64) -> bool {
for i in 2..=((x as f64).sqrt().floor() as u64) {
if x % i == 0 {
return false;
}
}
true
}
struct NthPrime {
count: usize,
value: u64,
}
impl NthPrime {
pub fn new(count: usize) -> Self {
NthPrime { count, value: 2 }
}
}
impl Future for NthPrime {
type Output = u64;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut data = self.get_mut();
if data.count == 0 {
Poll::Ready(data.value)
} else {
if is_prime(data.value + 1) {
data.count -= 1;
}
data.value += 1;
cx.waker().clone().wake();
Poll::Pending
}
}
}
async fn nth_prime(count: usize) -> u64 {
await!(NthPrime::new(count))
}
fn main() {
let nth = 100000;
let future = nth_prime(nth);
let prime = futures::executor::block_on(future);
println!("nth_prime({}) = {}", nth, prime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment