How to resolve the algorithm McNuggets problem step by step in the Kotlin programming language
How to resolve the algorithm McNuggets problem step by step in the Kotlin programming language
Table of Contents
Problem Statement
Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm McNuggets problem step by step in the Kotlin programming language
The provided Kotlin code determines the maximum non-McNuggets number up to a certain limit. A McNuggets number is a number that can be formed using only 6, 9, and 20 as factors.
Here's how the code works:
-
It initializes a Boolean array
sv
of sizelimit + 1
, wherelimit
is the maximum number to check. Initially, all elements insv
are set tofalse
. -
It iterates through three nested loops to populate
sv
. For each combination of factors (6, 9, and 20), it checks if the resulting number (e.g., 6, 9, 12, 15, ...) is within thelimit
. If it is, it sets the corresponding element insv
totrue
. -
After populating
sv
, it starts another loop that iterates in reverse order fromlimit
down to 0. -
For each number
i
in the reverse loop, it checks ifsv[i]
isfalse
. If it is, it means thati
cannot be formed using the factors 6, 9, and 20. Therefore, it prints thati
is the maximum non-McNuggets number and terminates the program. -
If the loop completes without finding a non-McNugget number, it means that all numbers up to
limit
can be formed using the given factors. In that case, it doesn't print anything.
In the main
function, it calls mcnugget(100)
to find the maximum non-McNuggets number up to 100. The output will be "Maximum non-McNuggets number is 43".
Source code in the kotlin programming language
// Version 1.2.71
fun mcnugget(limit: Int) {
val sv = BooleanArray(limit + 1) // all false by default
for (s in 0..limit step 6)
for (n in s..limit step 9)
for (t in n..limit step 20) sv[t] = true
for (i in limit downTo 0) {
if (!sv[i]) {
println("Maximum non-McNuggets number is $i")
return
}
}
}
fun main(args: Array<String>) {
mcnugget(100)
}
You may also check:How to resolve the algorithm Read entire file step by step in the Scala programming language
You may also check:How to resolve the algorithm Smith numbers step by step in the MAD programming language
You may also check:How to resolve the algorithm Determine if a string is collapsible step by step in the BQN programming language
You may also check:How to resolve the algorithm Index finite lists of positive integers step by step in the 11l programming language
You may also check:How to resolve the algorithm Singleton step by step in the Kotlin programming language