find the sum of the multiples of 3 and 5 below 1000

前端 未结 12 966
我在风中等你
我在风中等你 2021-01-18 08:04

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

12条回答
  •  抹茶落季
    2021-01-18 08:55

    Logics given above are showing wrong answer, because multiples of 3 & 5 are taken for calculation. There is something being missed in above logic, i.e., 15, 30, 45, 60... are the multiple of 3 and also multiple of 5. then we need to ignore such while adding.

        public static void main(String[] args) {
        int Sum=0, i=0, j=0;
        for(i=0;i<=1000;i++)
            if (i%3==0 && i<=999)
                Sum=Sum+i;
        for(j=0;j<=1000;j++)
            if (j%5==0 && j<1000 && j*5%3!=0)
                Sum=Sum+j;
        System.out.println("The Sum is "+Sum);
    }
    

提交回复
热议问题