Rust Implementation of Problem 35
View source code here on GitHub!
Includes
Problem Solution
- pub fn problems::p0035::p0035() -> utils::Answer
1/*
2Project Euler Problem 35
3
4Problem:
5
6The number, 197, is called a circular prime because all rotations of the
7digits: 197, 971, and 719, are themselves prime.
8
9There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71,
1073, 79, and 97.
11
12How many circular primes are there below one million?
13*/
14use crate::include::primes::is_prime;
15use crate::include::utils::Answer;
16
17pub fn p0035() -> Answer {
18 let mut answer: u64 = 0;
19 for x in 0..1000000 {
20 if Rotations::new(x).all(is_prime) {
21 answer += 1;
22 }
23 }
24 return Answer::Int(answer.into());
25}
26
27struct Rotations {
28 x: String,
29 i: usize,
30 n: u64,
31}
32
33impl Rotations {
34 pub fn new(x: u64) -> Self {
35 return Rotations{
36 x: x.to_string(),
37 i: 0,
38 n: x,
39 };
40 }
41}
42
43impl Iterator for Rotations {
44 type Item = u64;
45
46 fn next(&mut self) -> Option<Self::Item> {
47 if self.i == 0 {
48 self.i += 1;
49 return Some(self.n);
50 }
51 if self.i < self.x.len() {
52 let result = format!("{}{}", &self.x[self.i..], &self.x[..self.i]).parse::<u64>().unwrap();
53 self.i += 1;
54 return Some(result);
55 }
56 return None;
57 }
58}