Upload files to "ex1C_summation_of_specified_numbers"
This commit is contained in:
parent
c271205a39
commit
c70572f1b9
3 changed files with 64 additions and 0 deletions
28
ex1C_summation_of_specified_numbers/special_sum.cpp
Normal file
28
ex1C_summation_of_specified_numbers/special_sum.cpp
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
#include "special_sum.h"
|
||||
|
||||
size_t gauss_sum(size_t n)
|
||||
{
|
||||
return (n*(n+1))/2;
|
||||
}
|
||||
|
||||
size_t special_sum_loop(size_t n)
|
||||
{
|
||||
size_t sum = 0;
|
||||
for (size_t i = 1; i < n+1; ++i)
|
||||
{
|
||||
if (i % 3 == 0 || i % 5 == 0)
|
||||
{
|
||||
sum += i;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
size_t special_sum_noloop(size_t n)
|
||||
{
|
||||
size_t factor_3 = gauss_sum(n/3); // dividing int by int automatically gets rounded off
|
||||
size_t factor_5 = gauss_sum(n/5);
|
||||
size_t factor_15 = gauss_sum(n/15);
|
||||
|
||||
return factor_3*3 + factor_5*5 - factor_15*15;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue