[–] RevanProdigalKnight 0 points 1 points (+1|-0) ago  (edited ago)

Your euler function could still be made more deterministic and shorter than it is.

def euler_1():
    multiples = []
    
    counter = 1

    while True:
        # calculate the multiple of 3
        t = 3 * counter
        
        # If this is past 1000 we're done
        if t < 1000:
            # This may have already been added as a multiple of 5
            if t not in multiples:
                multiples.append(t)
            
            # Calculate the multiple of 5
            t = 5 * counter
            
            # Don't bother adding `and t not in multiples` because the
            # multiple of 5 will always be ahead of the multiple of 3
            if t < 1000:
                multiples.append(t)
                
            # Increment the counter for the next iteration
            counter += 1
        else:
            break

    print("Found {} total multiples.".format(len(multiples)))
    print("Sum: {}".format(sum(multiples)))

This finds the same answer in only 334 iterations

[–] RevanProdigalKnight 0 points 0 points (+0|-0) ago  (edited ago)

Equivalent JS code that I used to figure out the method beforehand (because my Python is a bit rusty):

function euler_1() {
  // Use `Set` because it accounts for duplicates already
  const multiples = new Set();
  let t; // Temporary number variable
  let i =0; // Counter

  // Increment counter, calculate multiple of 3. If >= 1000 we're done
  while ((t = 3 * ++i) < 1000) {
    multiples.add(t);
    if ((t = 5 * i) < 1000) { // Add multiple of 5 if it's also < 1000
      multiples.add(t);
    }
  }

  // Log the actual count of how many iterations it took rather than
  // taking the number of multiples as the iteration count
  console.log(`Found ${multiples.size} total multiples in ${i} iterations.`);
  // One-liner to get the sum of all the multiples
  console.log('Sum:', [...multiples].reduce((acc, n) => acc + n, 0));
}

[–] peacegnome 0 points 0 points (+0|-0) ago 

Less clear, but could be done with math. I might write it out later but basically "1000/3/5" is key

[–] omacu 0 points 0 points (+0|-0) ago 

Nice post

[–] rcb 1 points -1 points (+0|-1) ago  (edited ago)

Couldn't you do this?

N = 1000
x3 = N // 3
x5 = N // 5
x3_5 = N // (3*5)
print(x3 + x5 - x3_5)

EDIT Turns out you have to use // for integer division. Keep missing that!

Oh, sum not count... In that case

def triangle(n):
    "n'th triangle number"
    return n*(n+1) // 2 # forgot to integer divide again!

x3_sum = 3*triangle(x3)
x5_sum = 5*triangle(x5)
x3_5_sum = (3*5)*triangle(x3_5)
ans = x3_sum + x5_sum - x3_5_sum
print(ans)

[–] Satirical [S] 0 points 0 points (+0|-0) ago 

Ooh, triangle numbers. Clever.