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.
The sum of all multiples of k below n can be calculated using the formula
for the sum of an arithmetic progression:
S = n/2 * ([(n-1)/k] * [(n-1)/k + 1]) .
Where [(n-1)/k] represents the number of multiples of k below n.
Using this formula, we can calculate the sum of multiples of 3 and 5, and
then subtract the sum of multiples of 15 (to avoid double counting multiples of
both 3 and 5).
#include<stdio.h>// Function to calculate the sum of multiples of k below n using arithmetic progression formulalonglongsumOfMultiples(longlongk,longlongn){longlongp=(n-1)/k;// Number of multiples of k below nreturnk*p*(p+1)/2;// Sum of multiples of k}intmain(){intt;scanf("%d",&t);for(inta0=0;a0<t;a0++){longlongn;scanf("%lld",&n);// Calculate the sum of multiples of 3 and 5, and subtract the sum of multiples of 15longlongsum=sumOfMultiples(3,n)+sumOfMultiples(5,n)-sumOfMultiples(15,n);printf("%lld\n",sum);}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #1: Multiples of 3 and 5
You are viewing a single comment's thread. Return to all comments →