aboutsummaryrefslogtreecommitdiff
path: root/rust
diff options
context:
space:
mode:
Diffstat (limited to 'rust')
-rw-r--r--rust/001-multiples_of_3_and_5.rs18
-rw-r--r--rust/002-even_fibonacci_numbers.rs41
-rw-r--r--rust/003-largest_prime_factor.rs39
3 files changed, 98 insertions, 0 deletions
diff --git a/rust/001-multiples_of_3_and_5.rs b/rust/001-multiples_of_3_and_5.rs
new file mode 100644
index 0000000..ac30587
--- /dev/null
+++ b/rust/001-multiples_of_3_and_5.rs
@@ -0,0 +1,18 @@
+/*
+* Multiples of 3 and 5
+* Problem 1
+*
+* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
+* Find the sum of all the multiples of 3 or 5 below 1000.
+*/
+
+fn main() {
+ let mut sum = 0;
+
+ for x in 1..999 {
+ if x % 3 == 0 || x % 5 == 0 {
+ sum += x;
+ }
+ }
+ println!("{}", sum);
+}
diff --git a/rust/002-even_fibonacci_numbers.rs b/rust/002-even_fibonacci_numbers.rs
new file mode 100644
index 0000000..1f95f3a
--- /dev/null
+++ b/rust/002-even_fibonacci_numbers.rs
@@ -0,0 +1,41 @@
+/*
+* Even Fibonacci numbers
+* Problem 2
+*
+* Each new term in the Fibonacci sequence is generated by adding the previous two terms.
+* By starting with 1 and 2, the first 10 terms will be:
+* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
+* By considering the terms in the Fibonacci sequence whose values do not exceed four million,
+* find the sum of the even-valued terms.
+*/
+
+struct Fib {
+ a: u32,
+ b: u32
+}
+
+impl Iterator for Fib {
+ type Item = u32;
+
+ fn next(&mut self) -> Option<u32> {
+ let c = self.a + self.b;
+ self.a = self.b;
+ self.b = c;
+ return Some(c)
+ }
+}
+
+fn main() {
+ let fib = Fib { a: 0, b: 1 };
+ let mut sum = 0;
+
+ for f in fib {
+ if f > 4_000_000 {
+ break;
+ }
+ if f % 2 == 0 {
+ sum += f;
+ }
+ }
+ println!("{}", sum);
+}
diff --git a/rust/003-largest_prime_factor.rs b/rust/003-largest_prime_factor.rs
new file mode 100644
index 0000000..2b84df1
--- /dev/null
+++ b/rust/003-largest_prime_factor.rs
@@ -0,0 +1,39 @@
+/*
+* Largest prime factor
+* Problem 3
+*
+* The prime factors of 13195 are 5, 7, 13 and 29.
+* What is the largest prime factor of the number 600851475143 ?
+*/
+
+// fn is_prime(n: u64) -> bool {
+// if n == 2 || n == 3 || n == 5 || n == 7 {
+// return true;
+// }
+// if n % 2 == 0 || n % 3 == 0 {
+// return false;
+// }
+//
+// for i in (6..n).step_by(6) {
+// if n % (i - 1) == 0 || n % (i + 1) == 0 {
+// return true;
+// }
+// }
+// return false;
+// }
+
+fn main() {
+ let mut target: u64 = 600851475143;
+ let mut n: u64 = 2;
+ let mut last = 0;
+
+ while target > 1 {
+ if target % n == 0 {
+ last = n;
+ target /= n;
+ n = 2;
+ }
+ n += 1;
+ }
+ println!("{}", last);
+}