Project Euler #1: Multiples of 3 and 5

Sort by

recency

|

1466 Discussions

|

  • + 0 comments

    import Control.Applicative import Control.Monad import System.IO

    sumTo :: Integer -> Integer sumTo 0 = 0 sumTo n = (n * (n + 1)) div 2

    multSum :: Integer -> Integer multSum 0 = 0; multSum n = total_sum where three_max = n div 3; five_max = n div 5; fifteen_max = n div 15; three_mult = 3 * (sumTo three_max); five_mult = 5 * (sumTo five_max); fifteen_mult = 15 * (sumTo fifteen_max); total_sum = three_mult + five_mult - fifteen_mult

    main :: IO () main = do t_temp <- getLine let t = read t_temp :: Int forM_ [1..t] $ \a0 -> do n_temp <- getLine let n = read n_temp :: Integer let sum = multSum (n - 1) print (sum)

  • + 0 comments

    for(int a0 = 0; a0 < t; a0++){ int n = in.nextInt(); System.out.println(sumOfMultiples(n-1)); }}

    private static long sumOfMultiples(int n) { return sumDivisibleBy(n, 3) + sumDivisibleBy(n, 5) - sumDivisibleBy(n, 15); } private static long sumDivisibleBy(int n, int k) { int p = n / k; return k * (long)p * (p + 1) / 2; } }

  • + 1 comment

    Python, this is my sarcasticly built one line... But I keep getting a timeout on two of the tests. Tried basic for loop, itterating a value, sum a list, writing it all out line by line... [print(sum(map(lambda x: x if x % 3 ==0 or x % 5 == 0 else 0, range(3, int(input()))))) for _ in range(int(input()))]

  • + 0 comments

    int main(){ int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int n; cin >> n; long long sum=0;

    long  i= (n-1)/3 ,j = (n-1)/5 , k=(n-1)/15;
    sum= 3*(i*(i+1)/2)+ 5*(j*(j+1)/2) - 15*(k*(k+1)/2);
    
    cout<<sum<<"\n";
        }
    
  • + 0 comments

    Haskell

    import Control.Applicative
    import Control.Monad
    import System.IO
    
    
    sumTo :: Integer -> Integer
    sumTo 0 = 0
    sumTo n = (n * (n + 1)) `div` 2
    
    multSum :: Integer -> Integer
    multSum 0 = 0;
    multSum n = total_sum where
        three_max = n `div` 3;
        five_max = n `div` 5;
        fifteen_max = n `div` 15;
        three_mult = 3 * (sumTo three_max);
        five_mult = 5 * (sumTo five_max);
        fifteen_mult = 15 * (sumTo fifteen_max);
        total_sum = three_mult + five_mult - fifteen_mult 
    
    main :: IO ()
    main = do
        t_temp <- getLine
        let t = read t_temp :: Int
        forM_ [1..t] $ \a0  -> do
            n_temp <- getLine
            let n = read n_temp :: Integer
            let sum = multSum (n - 1)
            print (sum)