Project Euler #1: Multiples of 3 and 5

Sort by

recency

|

1448 Discussions

|

  • + 0 comments
    long long sum_of_multiples(int x, int n) {
        int p = (n - 1) / x; // Largest multiple of x below n
        return (long long)x * p * (p + 1) / 2; // Sum of multiples formula
    }
    int main(){
        int t; 
        scanf("%d",&t);
        for(int a0 = 0; a0 < t; a0++){
            int n; 
            scanf("%d",&n);
            // Sum of multiples of 3 and 5, minus multiples of 15 (to avoid double counting)
            long long sum = sum_of_multiples(3, n) + sum_of_multiples(5, n) - sum_of_multiples(15, n);
    
            printf("%lld\n", sum);
        }
        return 0;
    }
    
  • + 0 comments

    I cannot pass 2 of the tests with this Kotlin code, anybody has any idea?

    fun main(args: Array<String>) {
        val t = readLine()!!.trim().toInt()
    
        for (tItr in 1..t) {
            val n = readLine()!!.trim().toInt()
            println("${sumn(n,3)+sumn(n,5)-sumn(n,15)}")
            
        }
        
    }
    
    fun sumn(n:Int,d:Int):Int{
        val l = (n-1)/d
        return d*l*(l+1)/2
    }
    
  • + 3 comments
    time limit problem in this program ,help to solve the problem
    

    int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int sum =0; int n; cin >> n; for(int i = 3; i < n; i++){ if(i%3==0 || i%5==0){ sum+=i; } }

        cout<<sum<<endl;
    }
    
  • + 0 comments

    int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int sum =0; int n; cin >> n; for(int i = 3; i < n; i++){ if(i%3==0 || i%5==0){ sum+=i; } }

        cout<<sum<<endl;
    }
    
        time limit problem in this program ,help to solve the problem
    
    
    
    
    
    hgdshfhs
    
  • + 0 comments

    JAVA 8: Used sum of natural formula for calculation

    import java.util.Scanner;
    public class Solution {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            
            for(int i = 0; i < n; i++)
                { 
                    long a = sc.nextLong();
                    long x= (a-1)/3;
                    long y= (a-1)/5;
                    long z= (a-1)/15;
                    
                    long sum= (3*((x*(x+1))/2)) + (5*((y*(y+1))/2)) 
                            - (15*((z*(z+1))/2));
                    
                    System.out.println(sum);
                }
            sc.close();
            
         
    }
    }