首页 文章

显示等于X的所有硬币组合(四分之一,一角硬币,镍币,便士)

提问于
浏览
0

写一个程序,要求用户输入一个美元金额X.显示所有硬币组合(四分之一,一角钱,镍,一分钱)等于X.输入美元金额$:1.2 4季度,2角钱,0镍,0便士3季度,4角钱,1镍,0便士......

package p1;

public class Combination {

    public static void findCombination(Double value){

        int totalCents = (int) (value*100);

        int aq = totalCents/25;
        int ad = totalCents/10;
        int an = totalCents/5;
        int ap = totalCents;

        for(int q=0; q<= aq; q++){

            for(int d=0; d<= ad; d++){

                for(int n=0;n<= an; n++){

                    for(int p=0;p<=ap; p++){

                        if(((q*25) + (d*10) + (n*5) + p ) == totalCents){

                            System.out.println("Q: "+q+" D: "+d+" N: "+n+" P: "+p );

                        }
                    }
                }
            }
        }

有没有比这更优化的解决方案,我想不出一个 .

1 回答

  • 0

    您可以编辑for循环布尔值中使用的最大值 . 也许订单会被翻转 .

    就像是:

    int p=0, n=0, d=0, q=0;
    for(p=0; p <= (totalcents-q*25-d*10-n*5) ; p++){
    
        for(n=0; (n*5) <= (totalcents-q*25-d*10) ; n++){
    
            for(d=0; (d*10) <= (totalcents-q*25) ; d++){
    
                for(q=0; (q*25) <= totalcents ; q++){
    
                    if(((q*25) + (d*10) + (n*5) + p ) == totalCents){
    
                        System.out.println("Q: "+q+" D: "+d+" N: "+n+" P: "+p );
    
                    }
                }
            }
        }
    }
    

    我没有测试它是否会加速你的代码,但是在非常大的X值时,它可能比通过所有可能的Q D N P值更快,因为最大值减小了 .

    这种方式你也不需要:

    int aq = totalCents/25;
    int ad = totalCents/10;
    int an = totalCents/5;
    int ap = totalCents;
    

相关问题