Project Euler #1 in Java

前端 未结 8 1622
旧时难觅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 18:59

    You should do:

    for (int i = 0; i < 1000; i++) {
        if (i % 3 == 0 || i % 5 ==0) {
            temp += i;
        }
    }
    

    This will add each number only one time. In your code, you will add 15 twice, since it'll be satisfied in both conditions in both loops.

    Also note that according to the requirements, you should loop to < 1000, not <=.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题