小易去买苹果,有两种包装,一种一袋8个,一种一袋6个,小易要买n个苹果(不能多也不能少),输出袋子最少的购买方案,如无法正好买到n个,则输出-1.
public class BuyApple {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("输入一个整数:");
int n = input.nextInt();
int[] min = buyApple(n);
if(min[0] == n){
System.out.println(-1);
}else{
System.out.println("最少需要"+min[0]+"袋,其中:8个苹果"+min[1]+"袋、6个苹果"+min[2]+"袋");
}
}
public static int[] buyApple(int n) {
int min = n;
int[] results = {n,0,0};//总袋数,8个的袋数,6个的袋数
if(n%8 == 0){
results[0] = n/8;
results[1] = n/8;
}else if(n%6 == 0){
if(n/6 < results[0]){
results[0] = n / 6;
results[1] = n / 6;
}
}else{
for(int i = 0; i <= n/8; ++i){
if((n-8*i)%6 == 0){
if((n-8*i)/6 + i < min){
results[0] = (n-8*i)/6 + i;
results[1] = i;
results[2] = (n-8*i)/6;
}
}
}
}
return results;
}
}