Solution 1: Check Divisibility by 3 and 4
Solution:
fn test_divisibility_by_3_4(a:i32)->i32{
//check if number is divisible by 3 and 4
if a % 3 == 0 && a % 4 == 0{
0
}
//check if number is divisible by 3 and not by 4
else if a % 3 == 0 && a % 4 != 0 {
1
}
//check if number is divisible not by 3 but 4
else if a % 3 != 0 && a % 4 == 0 {
2
}
//check if neither divisible by 3 nor 4
else {
-1
}
}
fn main(){
println!(" Number = 12 : {}", test_divisibility_by_3_4(12));
println!(" Number = 9 : {}", test_divisibility_by_3_4(9));
println!(" Number = 8 : {}", test_divisibility_by_3_4(8));
println!(" Number = 23 : {}", test_divisibility_by_3_4(23));
}
output
Number = 12 : 0
Number = 9 : 1
Number = 8 : 2
Number = 23 : -1
Explanation
The test_divisibility_by_3_4
takes an integer a as a parameter to the function and returns an integer of type i32
.
- On line `3`, the if condition checks if the number a is divisible by `3` and `4`, it `returns 0` on `line 4`.
- On line `7`, the else if executes if the if condition fails.
- The condition checks if the number a is divisible by 3 and not by 4, it `returns 1` on line `8`.
- On line `11`, the else if executes if the first else if condition fails.
- The condition checks if the number a is not divisible by 3 but by 4, it `returns 2` on line `12`.
- On line `15`, the else, executes if all the above conditions fail and `returns -1` on line `16`.