Given a positive integer n
, return the smallest positive integer that is a multiple of both 2
and n
.
Example 1:
Input: n = 5 Output: 10 Explanation: The smallest multiple of both 5 and 2 is 10.
Example 2:
Input: n = 6 Output: 6 Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself.
Constraints:
1 <= n <= 150
program main
implicit none
integer, parameter :: n = 5
integer :: result
result = smallestMultiple(n)
print '(I0)', result
contains
function smallestMultiple(n) result(result_)
implicit none
integer, value :: n
integer :: result_
result_ = 2 * (n - 1) + 1
end function smallestMultiple
end program main
9
PROGRAM MULTIPLE_OF_2_AND_N
IMPLICIT NONE
INTEGER, PARAMETER :: n = 5
INTEGER :: i, j, k
! Initialize the smallest multiple of 2 and n to 0
i = 0
j = 0
! Loop through all positive integers
DO k = 1, 150
! Check if k is a multiple of 2
IF (MODULO(k, 2) == 0) THEN
i = k
END IF
! Check if k is a multiple of n
IF (MODULO(k, n) == 0) THEN
j = k
END IF
! If k is a multiple of both 2 and n, break the loop
IF (MODULO(k, 2) == 0 .AND. MODULO(k, n) == 0) THEN
EXIT
END IF
END DO
! Print the smallest multiple of 2 and n
WRITE (*, *) "The smallest multiple of 2 and ", n, " is ", i * j
END PROGRAM MULTIPLE_OF_2_AND_N
The smallest multiple of 2 and 5 is 100
def smallest_multiple(n):
return n if n % 2 == 0 else n * 2
The algorithm to solve this problem is quite simple. The smallest positive integer that is a multiple of both 2 and n
can be determined by checking if n
is even or odd. If n
is even, it means that it is already a multiple of 2, so the answer should be n
. If n
is odd, we need to multiply n
by 2 to get the smallest multiple that is also divisible by 2, so the answer should be n * 2
.
int smallestMultiple(int n) {
return n % 2 == 0 ? n : n * 2;
}
The algorithm to solve this problem is quite simple. The smallest positive integer that is a multiple of both 2 and n
can be determined by checking if n
is even or odd. If n
is even, it means that it is already a multiple of 2, so the answer should be n
. If n
is odd, we need to multiply n
by 2 to get the smallest multiple that is also divisible by 2, so the answer should be n * 2
.