Contents

Sharing a Pizza 2 (with.Java)

   Jan 6, 2024     2 min read

This is a recap of the “Share a Pizza 2” problem.

We’re going to learn by solving coding test problems, reflecting on the problems we’ve solved, and exploring other ways to solve them.

Let’s start with the problem.

Problem

A pizza parlor cuts a pizza into six slices.

Given the number n of people to share the pizza as a parameter, complete the solution function so that it returns the minimum number of slices that should be ordered if n people are to eat the same number of slices without leaving any leftovers.

Example input and output

nresult
61
105
42

My solution to the ### problem

class Solution {
	public int solution(int n) {
		int answer = 0;
		for (int i = 1; i <= 6 * n; i++) {
			if (6 * i % n == 0) {
				answer = i;
				break;
			}
		}
    } return answer;
}

solution description

int answer = 0;: Initialize the variable answer to store the resulting value.

for (int i = 1; i <= 6 _ n; i++) : Iterate over i in multiples of 1 through 6 _ n. This is because no matter how big it is, it will never go over the value of 6 * n. This is because no matter how large it is, it will never exceed the value of 6 * n.

if (6 * i % n == 0): check if the value multiplied by 6 for the current i is divisible by n.

answer = i;: If it does, store the current value of i in answer and end the loop.

break;: If the condition is satisfied, end the loop.

return answer;: Returns the calculated result, answer.

This code finds the first number that is divisible by n among multiples of 6.

If n is a multiple of 6, answer will be 1. Otherwise, the smallest number among the multiples of n is returned as answer.