Exercises_MarkusSchmidt/sheet1/C/main.cpp
Markus Schmidt d3aa42a3e0 Solutions
2025-10-21 19:36:38 +02:00

70 lines
1.7 KiB
C++

#include <iostream>
#include "timing.h"
using namespace std;
unsigned long multiplesOf3Or5(unsigned int n)
{
unsigned long sum = 0;
for(unsigned int i=1; i<=n; i++)
{
if(i % 3 == 0 || i % 5 == 0)
{
sum += i;
}
}
return sum;
}
unsigned long gauss_sum(unsigned long n)
{
return n*(n+1)/2;
}
unsigned long multiplesOf3Or5_noLoop(unsigned int n)
{
/*for n there are floor(n/3) multiples of 3 and floor(n/5) multiples of 5. Calculate them using Gauss summation and subtract the
multiples of 15 (counted twice)*/
unsigned long multiples3 = gauss_sum(n/3)*3;
unsigned long multiples5 = gauss_sum(n/5)*5;
unsigned long multiples15 = gauss_sum(n/15)*15;
return multiples3 + multiples5 - multiples15;
}
int main() {
unsigned long mA,mB,mC,mD,mE,mF;
tic();
for(unsigned int i = 0; i< 10000; i++)
{
mA = multiplesOf3Or5(15);
mB = multiplesOf3Or5(1001);
mC = multiplesOf3Or5(1432987);
}
double timeA = toc();
tic();
for(unsigned int i = 0; i< 10000; i++)
{
mD = multiplesOf3Or5_noLoop(15);
mE = multiplesOf3Or5_noLoop(1001);
mF = multiplesOf3Or5_noLoop(1432987);
}
double timeB = toc();
cout << "n = 15, result = " << mA << endl;
cout << "n = 1001, result = " << mB << endl;
cout << "n = 1432987, result = " << mC << endl;
cout << "time: " << timeA << endl;
cout << "--------------------------------------------------------------" <<endl;
cout << "n = 15, result = " << mD << endl;
cout << "n = 1001, result = " << mE << endl;
cout << "n = 1432987, result = " << mF << endl;
cout << "time: " << timeB << endl;
return 0;
}