[Programmers / JAVA] Level 1 Finding the Number Whose Remainder Is 1 (87389)
[Programmers / JAVA] Level 1 Finding the Number Whose Remainder Is 1 (87389)
A natural number n is given as a parameter. Complete the solution function to return the smallest natural number x such that the remainder when n is divided by x is 1. It can be proven that an answer always exists.
@RWBwritten at 2021-12-15 14:36:45
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
🔗 Finding the Number Whose Remainder Is 1
A natural number n is given as a parameter. Complete the solution function to return the smallest natural number x such that the remainder when n is divided by x is 1. It can be proven that an answer always exists.
- 3 ≤ n ≤ 1,000,000
| n | result |
|---|---|
| 10 | 3 |
| 12 | 11 |
Example #1
The remainder when 10 is divided by 3 is 1, and there is no smaller natural number than 3 that satisfies the condition, so return 3.
Example #2
The remainder when 12 is divided by 11 is 1, and there is no smaller natural number than 11 that satisfies the condition, so return 11.
There's no particular trick here. Simply return the smallest number x such that dividing the natural number n by it leaves a remainder of 1.
Just start with x = 1 and increment x until n % x == 1.
JAVA
/** * Finding the Number Whose Remainder Is 1 class * * @author RWB * @since 2021.12.12 Sun 16:35:58 */ class Solution { /** * Method that returns the answer * * @param n: [int] natural number * * @return [int] answer */ public int solution(int n) { int x = 1; while (n % x != 1) { x++; } return x; } }
# Programmers# Algorithm# JAVA# Level 1
