forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add another Perfect Cube implementation (TheAlgorithms#651)
- Loading branch information
1 parent
3a1724d
commit 5f1c45a
Showing
3 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
pub fn perfect_cube(n: i32) -> bool { | ||
// Calculate the cube root using floating-point arithmetic. | ||
let val = (n as f64).powf(1.0 / 3.0); | ||
// Check if the cube of the cube root equals the original number. | ||
(val * val * val) == (n as f64) | ||
} | ||
|
||
// Check if a number is a perfect cube using binary search. | ||
pub fn perfect_cube_binary_search(n: i64) -> bool { | ||
// Handle negative numbers, as cube roots are not defined for negatives. | ||
if n < 0 { | ||
return false; | ||
} | ||
|
||
// Initialize left and right boundaries for binary search. | ||
let mut left = 0; | ||
let mut right = n.abs(); // Use the absolute value to handle negative numbers | ||
|
||
// Binary search loop to find the cube root. | ||
while left <= right { | ||
// Calculate the mid-point. | ||
let mid = left + (right - left) / 2; | ||
// Calculate the cube of the mid-point. | ||
let cube = mid * mid * mid; | ||
|
||
// Check if the cube equals the original number. | ||
match cube.cmp(&n) { | ||
std::cmp::Ordering::Equal => return true, | ||
std::cmp::Ordering::Less => left = mid + 1, | ||
std::cmp::Ordering::Greater => right = mid - 1, | ||
} | ||
} | ||
|
||
// If no cube root is found, return false. | ||
false | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn test_perfect_cube() { | ||
assert!(perfect_cube_binary_search(27)); | ||
assert!(!perfect_cube_binary_search(4)); | ||
} | ||
|
||
#[test] | ||
fn test_perfect_cube_binary_search() { | ||
assert!(perfect_cube_binary_search(27)); | ||
assert!(perfect_cube_binary_search(64)); | ||
assert!(!perfect_cube_binary_search(4)); | ||
assert!(!perfect_cube_binary_search(-8)); | ||
} | ||
} |