We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Project Euler #1: Multiples of 3 and 5
Project Euler #1: Multiples of 3 and 5
Contest ends in
+ 0 comments My solution in C
#include <stdio.h> int main(){ int t; scanf("%d",&t); for(int a0 = 0; a0 < t; a0++){ int n; scanf("%d",&n); n--; long long sum = 0; long long num3 = n / 3; long long num5 = n / 5; long long num15 = n / 15; sum = 3 * num3 * (num3 + 1) / 2 + 5 * num5 * (num5 + 1) / 2 - 15 * num15 * (num15 + 1) / 2; printf("%lld\n", sum); } return 0; }
+ 0 comments This is my Java solution, feel free to ask me any questions.
private static long calculateSum(int n) { n--; // We want multiples below n, // so decrement n by 1 long sum = 0; if (n >= 3) { long mulThree = n / 3; sum += 3 * mulThree * (mulThree + 1) / 2; } if (n >= 5) { long mulFive = n / 5; sum += 5 * mulFive * (mulFive + 1) / 2; } // Remove duplicates if (n >= 15) { long mulFifteen = n / 15; sum -= 15 * mulFifteen * (mulFifteen + 1) / 2; } return sum; }
+ 0 comments Java solution
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; 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(); // Multiples under n, so decreasing n by 1 n = n-1; // sum of all multiples of 3 BigInteger p = BigInteger.valueOf(n/3); BigInteger s3 = BigInteger.valueOf(3).multiply(p).multiply(p.add(BigInteger.valueOf(1))).divide(BigInteger.valueOf(2)); // sum of all multiples of 5 p = BigInteger.valueOf(n/5); BigInteger s5 = BigInteger.valueOf(5).multiply(p).multiply(p.add(BigInteger.valueOf(1))).divide(BigInteger.valueOf(2)); // sum of all multiples of 15 p = BigInteger.valueOf(n/15); BigInteger s15 = BigInteger.valueOf(15).multiply(p).multiply(p.add(BigInteger.valueOf(1))).divide(BigInteger.valueOf(2)); System.out.println(s3.add(s5).subtract(s15)); } } }
+ 0 comments does this problem require knowledge of data structures and algorithms?
+ 0 comments long long sumDivisableBy(long long num, long long target) { long long p = (--target) / num; return num * p * (p + 1) / 2; } int main() { int t; cin >> t; for (int a0 = 0; a0 < t; a0++) { int n; cin >> n; cout << sumDivisableBy(5, n) + sumDivisableBy(3, n) - sumDivisableBy(15, n) << endl; } return 0; }
Load more conversations
Sort 1245 Discussions, By:
Please Login in order to post a comment