2021-03-22: Xiaohu goes to buy Apple, the store only provides two types of plastic bags, each type has any number. 1. Can hold 6

2021-03-22: Xiaohu goes to buy Apple, the store only provides two types of plastic bags, each type has any number. 1. A bag that can hold 6 apples, 2. A bag that can hold 8 apples. Xiaohu is free to use two kinds of bags to hold apples, but Xiaohu has obsessive-compulsive disorder. He requires that the number of bags he uses must be the least, and every bag he uses must be full. Given a positive integer N, return at least how many bags are used. If N cannot make each bag used must be full, return -1.

Fu Da's answer on March 22, 2021:

1. Natural wisdom is enough.
N must be a multiple of 2, otherwise the two bags will always be dissatisfied because the least common multiple of 6 and 8 is 2.
Put all bags in No. 8 bags first, and put the remaining apples in No. 6 bags. No. 6 is dissatisfied. Pour a No. 8 bag of apples into No. 6 bag until the No. 6 bag is full.

2. Reverse the results based on the results and find the rules.
N must be a multiple of 2, otherwise the two bags will always be unfilled, because the least common multiple of 6 and 8 is 2.
When N is greater than or equal to 18, starting from 18, a group of 8 numbers.
When N is less than 18, the result is directly given.

The code is written in golang, the code is as follows:

package main

import "fmt"

func main() {
    for apple := 100; apple <= 120; apple++ {
        fmt.Println(apple, " : ", minBages1(apple), " : ", minBages2(apple))
    }
}
func minBages1(apple int) int {
    if apple < 0 {
        return -1
    }
    bag8 := apple / 8
    rest := apple - bag8*8
    for bag8 >= 0 {
        // rest 个
        if rest%6 == 0 {
            return bag8 + (rest / 6)
        } else {
            bag8--
            rest += 8
        }
    }
    return -1
}
func minBages2(apple int) int {
    if (apple & 1) != 0 { // 如果是奇数,返回-1
        return -1
    }
    if apple < 18 {
        if apple == 0 {
            return 0
        }
        if apple == 6 || apple == 8 {
            return 1
        }
        if apple == 12 || apple == 14 || apple == 16 {
            return 2
        }
        return -1
    }
    return (apple-18)/8 + 3
}

The execution results are as follows:
Insert picture description here


Left God java code
comment

Guess you like

Origin blog.51cto.com/14891145/2668704