Project Euler #1 in Java

前端 未结 8 1768
旧时难觅i
旧时难觅i 2021-02-04 18:22

I\'m having problems with this code. I don\'t want to look at others, so I\'m wondering what\'s wrong with mine.

If we list all the natural numbers below 10 that are mu

8条回答
  •  故里飘歌
    2021-02-04 19:00

    Your code is incorrect because of a simple issue: there are numbers which can be divided by 3 and 5 as well. In your code, you count them twice: once in the first loop, and secondly in the second loop. What you should do, is one of the options below:

    A. Just run one loop and use two conditions instead of one: check if the number can be divided by 3 and also can be divided by 5 - then, and just then, add it to the total sum.

    B. I made a Python code, using the same method as you used, but with an added condition. It's absolutely not recommended and not efficient, but it may help you to understand better.

    numlist = []
    
    for i in range (1, 1000):
        if i % 3 == 0:
            numlist.append(i)
    
    
    for j in range (1, 1000):
        if j % 5 == 0:
            if not j in numlist:
                numlist.append(j)
    
    
    counter = 0
    for a in numlist:
        counter += a
    
    
    print counter
    

提交回复
热议问题