I have a question about a Project Euler question and optimization using loop unrolling.
Problem description: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
Solution:
#include <iostream>
#include <limits.h>
#include <stdio.h>
#include <time.h>
using namespace std;
int main() {
clock_t startTime = clock();
for (int i = 1; i < INT_MAX; i++)
{
bool isDivisible = true;
//CODE BLOCK #1
/*for (int j = 2; j <= 20; j++)
{
if ( i % j != 0)
{
isDivisible = false;
break;
{
}*/
//CODE BLOCK #2
/*if (i % 2 != 0 || i % 3 != 0 ||
i % 4 != 0 || i % 5 != 0 ||
i % 6 != 0 || i % 7 != 0 ||
i % 8 != 0 || i % 9 != 0 ||
i % 10 != 0 || i % 11 != 0 ||
i % 12 != 0 || i % 13 != 0 ||
i % 14 != 0 || i % 15 != 0 ||
i % 16 != 0 || i % 17 != 0 ||
i % 18 != 0 || i % 19 != 0 ||
i % 20 != 0 )
isDivisible = false;*/
if (isDivisible)
{
cout << "smallest: " << i << endl;
cout << "Ran in: " << clock() - startTime << " cycles" << endl;
break;
}
}
return 0;
}
Now, commenting out either CODE BLOCK #1 or CODE BLOCK #2 gives me the correct answer (232792560). However, CODE BLOCK #2 much faster than CODE BLOCK #1.
CODE BLOCK #1: 3,580,000 cycles (I just added the break into CODE BLOCK #1 and it runs much faster. Still significantly slower than the compound IF statement, however.)
CODE BLOCK #2: 970,000 cycles
Does anyone know why this huge performance difference might occur?