2413.最小偶倍数
链接:2413.最小偶倍数
难度:Easy
标签:数学、数论
简介:给你一个正整数 n ,返回 2 和 n 的最小公倍数(正整数)。
题解 1 - rust
- 编辑时间:2023-04-21
- 内存消耗:2.1MB
- 编程语言:rust
- 解法介绍:同上。
fn gcd(a: i32, b: i32) -> i32 {
    if a < b {
        gcd(b, a)
    } else if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}
impl Solution {
    pub fn smallest_even_multiple(n: i32) -> i32 {
        let res = gcd(2, n);
        let mut num = 2 * n / res;
        if num % 2 != 0 {
            num *= 2;
        }
        num
    }
}
题解 2 - python
- 编辑时间:2023-04-21
- 执行用时:52ms
- 内存消耗:14.7MB
- 编程语言:python
- 解法介绍:同上。
def gcd(a: int, b: int):
    if a < b:
        return gcd(b, a)
    if b == 0:
        return a
    return gcd(b, a % b)
class Solution:
    def smallestEvenMultiple(self, n: int) -> int:
        res = gcd(2, n)
        num = 2*n/res
        if num % 2 != 0:
            num *= 2
        return int(num) 
题解 3 - cpp
- 编辑时间:2023-04-21
- 内存消耗:5.8MB
- 编程语言:cpp
- 解法介绍:gcd。
int gcd(int a, int b) {
    if (a < b) return gcd(b, a);
    if (b == 0) return a;
    return gcd(b, a % b);
}
class Solution {
public:
    int smallestEvenMultiple(int n) {
        int res = gcd(2, n), num = 2 * n / res;
        if (num % 2 != 0) num *= 2;
        return num;
    }
};