Project Euler #1: Multiples of 3 and 5

Sort by

recency

|

1454 Discussions

|

  • + 0 comments

    handle long only:

    public class Solution {
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int t = in.nextInt();
            for(int a0 = 0; a0 < t; a0++){
                int n = in.nextInt()-1;
                //code below:
    						
                long ans=(3*sum(n/3))+(5*sum(n/5))-(15*sum(n/15));
                System.out.println(ans);
                
                //code above:
                
            }
        }
        
        public static long sum(long num){
            return (num*(num+1))/2;
        }
    }
    
  • + 1 comment

    t = int(input().strip()) for a0 in range(t): n = int(input().strip()) c=0 for p in range(n): if p%3==0 or p%5==0 and p%15!=0: c=c+p print(c) why time limit exceed in this code

  • + 0 comments

    def sum_multiples(k, n): m = (n - 1) // k return k * m * (m + 1) // 2

    if name == 'main': t = int(input().strip())

    for _ in range(t):
        n = int(input().strip())  
        result = sum_multiples(3, n) + sum_multiples(5, n) - sum_multiples(15, n)
        print(result)
    
  • + 0 comments

    It runs well but when I try sending code, it times out in test 2 and 3.

        var t = parseInt(readLine());
        for(var a0 = 0; a0 < t; a0++){
            var qtt3 = 0, qtt5 = 0, rep = 0;
            var n = parseInt(readLine());
            for(var i=1; i<n; i++){
                if(i%3===0) qtt3 += i
                if(i%5===0) qtt5 += i
                if(i%3===0 && i%5===0) rep += i
            }
            console.log(qtt3 + qtt5 - rep)
        }
    
  • + 0 comments

    KOTLIN Code

    • TC 2 & 3 checks if your code handles large numbers, use Long instead of Int.
    private fun calculateMultipleSums(n: Int){
        /*
            100/3 = 33
            100/5 = 20
            100/15 = 6        
        
            (n*(n+1))/2
        */
    		
        val sumOfThree = 3* findSum(findMultiplier(n, 3))
        val sumOfFive = 5* findSum(findMultiplier(n, 5))
        val sumOfFifteen = 15* findSum(findMultiplier(n, 15))
        
        println( sumOfThree +sumOfFive - sumOfFifteen)
    }
    
    private fun findSum(n: Long): Long{
        return (n * (n+1))/2
    }
    private fun findMultiplier(n: Int, m: Long): Long{
        return ((n-1)/m)
    }