Skip to content

Commit ff075b6

Browse files
1 parent 5e0824b commit ff075b6

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ These are for demonstration purposes only.
5353

5454
- [x] [Amicable numbers below N](./src/math/amicable_numbers.rs)
5555
- [x] [Baby-Step Giant-Step Algorithm](./src/math/baby_step_giant_step.rs)
56+
- [x] [Ceil](./src/math/ceil.rs)
5657
- [x] [Chinese Remainder Theorem](./src/math/chinese_remainder_theorem.rs)
5758
- [x] [Extended euclidean algorithm](./src/math/extended_euclidean_algorithm.rs)
5859
- [x] [Fast Inverse Square Root 'Quake' Algorithm](./src/math/square_root.rs)

src/math/ceil.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// In mathematics and computer science, the ceiling function maps x to the least integer greater than or equal to x
2+
// Source: https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
3+
4+
pub fn ceil(x: f64) -> f64 {
5+
let x_round = x.round();
6+
if (x_round * 10.0).round() < (x * 10.0).round() {
7+
x_round + 1.0
8+
} else {
9+
x_round
10+
}
11+
}
12+
13+
#[cfg(test)]
14+
mod tests {
15+
use super::*;
16+
17+
#[test]
18+
fn positive_decimal() {
19+
let num = 1.10;
20+
assert_eq!(ceil(num), num.ceil());
21+
}
22+
23+
#[test]
24+
fn positive_integer() {
25+
let num = 1.00;
26+
assert_eq!(ceil(num), num.ceil());
27+
}
28+
29+
#[test]
30+
fn negative_decimal() {
31+
let num = -1.10;
32+
assert_eq!(ceil(num), num.ceil());
33+
}
34+
35+
#[test]
36+
fn negative_integer() {
37+
let num = -1.00;
38+
assert_eq!(ceil(num), num.ceil());
39+
}
40+
41+
#[test]
42+
fn zero() {
43+
let num = 0.00;
44+
assert_eq!(ceil(num), num.ceil());
45+
}
46+
}

src/math/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
mod amicable_numbers;
22
mod armstrong_number;
33
mod baby_step_giant_step;
4+
mod ceil;
45
mod chinese_remainder_theorem;
56
mod collatz_sequence;
67
mod doomsday;
@@ -37,6 +38,7 @@ mod zellers_congruence_algorithm;
3738
pub use self::amicable_numbers::amicable_pairs_under_n;
3839
pub use self::armstrong_number::is_armstrong_number;
3940
pub use self::baby_step_giant_step::baby_step_giant_step;
41+
pub use self::ceil::ceil;
4042
pub use self::chinese_remainder_theorem::chinese_remainder_theorem;
4143
pub use self::collatz_sequence::sequence;
4244
pub use self::doomsday::get_week_day;

0 commit comments

Comments
 (0)