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

前端 未结 12 1046
我在风中等你
我在风中等你 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:43

    In a mathematical perspective,
    You did not consider about common factors between 3 and 5.
    Because there is double counting.


    ex; number 15 , 30 , 45 , 60 , 75 , 90 , 105 , 120 , 135 , 150 , 165 , 180 , 195 , 210 , 225 , 240 , 255 , 270 , 285 , 300 , 315 , 330 , 345 , 360 , 375 , 390 , 405 , 420 , 435 , 450 , 465 , 480 , 495 , 510 , 525 , 540 , 555 , 570 , 585 , 600 , 615 , 630 , 645 , 660 , 675 , 690 , 705 , 720 , 735 , 750 , 765 , 780 , 795 , 810 , 825 , 840 , 855 , 870 , 885 , 900 , 915 , 930 , 945 , 960 , 975 , 990 , are common factors.

    total of common factors = 33165.
    Your answer is 266333
    Correct answer is 233168.
    Your Answer - Total of common factors
    266333-33165=233168.

    (this is a code for getting common factors and Total of common factors )

    public static void main(String[] args) {
    
    System.out.println("The sum of the Common Factors : " + getCommonFactorSum());
    
    }
    
    private static int getCommonFactorSum() {
    int sum = 0;
    for (int i = 1; i < 1000; i++) {
        if (i % 3 == 0 && i % 5 == 0) {
            sum += i;
            System.out.println(i);
        }
    }
    

提交回复
热议问题