blog.itcode.devblog.itcode.dev

[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.

[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.
RWB0104
@RWBwritten at 2021-12-15 14:36:45
Programmers

시리즈 모아보기

Programmers

29 / 78
RankLanguage 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
nresult
103
1211

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
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08