Sum multiples of 3 and 5: Difference between revisions

m (→‎{{header|C#}}: Changed "C#" to "C sharp")
Line 102:
<pre>233168
2333333333333333333316666666666666666668</pre>
 
=={{header|C}}==
===Simple version===
<lang c>#include <stdio.h>
#include <stdlib.h>
 
unsigned long long sum35(unsigned long long limit)
{
unsigned long long sum = 0;
for (unsigned long long i = 0; i < limit; i++)
if (!(i % 3) || !(i % 5))
sum += i;
return sum;
}
 
int main(int argc, char **argv)
{
unsigned long long limit;
 
if (argc == 2)
limit = strtoull(argv[1], NULL, 10);
else
limit = 1000;
 
printf("%lld\n", sum35(limit));
return 0;
}</lang>
{{Out}}
<pre>$ ./a.out
233168
$ ./a.out 12345
35553600</pre>
 
===Fast version with arbitrary precision===
{{libheader|GMP}}
<lang c>#include <stdio.h>
#include <gmp.h>
 
void sum_multiples(mpz_t result, const mpz_t limit, const unsigned f)
{
mpz_t m;
mpz_init(m);
mpz_sub_ui(m, limit, 1);
mpz_fdiv_q_ui(m, m, f);
 
mpz_init_set(result, m);
mpz_add_ui(result, result, 1);
mpz_mul(result, result, m);
mpz_mul_ui(result, result, f);
mpz_fdiv_q_2exp(result, result, 1);
 
mpz_clear(m);
}
 
int main(int argc, char **argv)
{
mpf_t temp;
mpz_t limit;
 
if (argc == 2)
{
mpf_init_set_str(temp, argv[1], 10);
mpz_init(limit);
mpz_set_f(limit, temp);
mpf_clear(temp);
}
else
mpz_init_set_str(limit, "1000000000000000000000", 10);
 
mpz_t temp_sum;
mpz_t sum35;
mpz_init(temp_sum);
sum_multiples(temp_sum, limit, 3);
mpz_init_set(sum35, temp_sum);
sum_multiples(temp_sum, limit, 5);
mpz_add(sum35, sum35, temp_sum);
sum_multiples(temp_sum, limit, 15);
mpz_sub(sum35, sum35, temp_sum);
 
mpz_out_str(stdout, 10, sum35);
puts("");
 
mpz_clear(temp_sum);
mpz_clear(sum35);
mpz_clear(limit);
return 0;
}</lang>
{{Out}}
<pre>$ ./a.out
233333333333333333333166666666666666666668
$ ./a.out 23e45
123433333333333333333333333333333333333333333314166666666666666666666666666666666666666666668</pre>
 
=={{header|C sharp|C#}}==