Skip to content

Instantly share code, notes, and snippets.

@ruanpetterson
Last active October 21, 2022 12:39
Show Gist options
  • Save ruanpetterson/2f1502c4558e11e019f9756411998826 to your computer and use it in GitHub Desktop.
Save ruanpetterson/2f1502c4558e11e019f9756411998826 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
static void usage()
{
cerr << "usage: fibonacci N" << endl;
}
int main(int argc, char *argv[])
{
unsigned short n;
unsigned long long a, b, c;
if (argc == 1 || argc > 2)
{
usage();
return EXIT_FAILURE;
}
n = atoi(argv[1]);
a = 0, b = 1;
for (int i = 0; i < n; i++)
{
c = a;
a = b;
b = c + a;
cout << a << endl;
}
return EXIT_SUCCESS;
}
use std::{env, fmt};
pub struct Fibonacci {
current: u64,
next: u64,
}
impl Fibonacci {
pub const fn new() -> Fibonacci {
Fibonacci {
current: 0,
next: 1,
}
}
}
impl Default for Fibonacci {
fn default() -> Self {
Self::new()
}
}
impl Iterator for Fibonacci {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let new_next = self.current + self.next;
self.current = self.next;
self.next = new_next;
Some(self.current)
}
}
impl fmt::Display for Fibonacci {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.current.fmt(f)
}
}
pub fn usage() {
eprintln!("usage: fibonacci <n>");
}
fn main() -> Result<(), ()> {
let args: Vec<String> = env::args().collect();
if args.len() == 1 || args.len() > 2 {
usage();
return Ok(());
}
if let Ok(n) = &args[1].parse::<usize>() {
let fib = Fibonacci::new();
for i in fib.take(*n) {
println!("{}", i);
}
Ok(())
} else {
usage();
Err(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let fib = Fibonacci::new();
assert_eq!(
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55].as_slice(),
fib.take(10).collect::<Vec<_>>()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment