找出1000以下3和5的倍数之和 [英] find the sum of the multiples of 3 and 5 below 1000

查看:59
本文介绍了找出1000以下3和5的倍数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我正在做Euler项目的挑战,我简直不敢相信我被困在第一个挑战.尽管我的代码看起来很正常,但我真的看不到为什么我得到错误的答案:

Ok guys, so I'm doing the Project Euler challenges and I can't believe I'm stuck on the first challenge. I really can't see why I'm getting the wrong answer despite my code looking functional:

import java.util.ArrayList;


public class Multithree {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Integer> x = new ArrayList<Integer>();
        ArrayList<Integer> y = new ArrayList<Integer>();
        int totalforthree = 0;
        int totalforfive = 0;

        int total =0;

        for(int temp =0; temp < 1000 ; temp++){
            if(temp % 3 == 0){
                x.add(temp);
                totalforthree += temp;
            }
        }

        for(int temp =0; temp < 1000 ; temp++){
            if(temp % 5 == 0){
                y.add(temp);
                totalforfive += temp;
            }
        }

        total = totalforfive + totalforthree;



        System.out.println("The multiples of 3 or 5 up to 1000 are: " +total);

    }

}

我得到的答案是266333,它说错了...

I'm getting the answer as 266333 and it says it's wrong...

推荐答案

您应该对两者都使用相同的for循环,以避免重复计算两者的倍数.例如15,30 ...

you should use the same for loop for both to aviod double counting numbers that are multiple of both. such as 15,30...

   for(int temp =0; temp < 1000 ; temp++){
        if(temp % 3 == 0){
            x.add(temp);
            totalforthree += temp;
        }else if(temp % 5 == 0){
            y.add(temp);
            totalforfive += temp;
        }
    }

这篇关于找出1000以下3和5的倍数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆