Project Euler problem 12: highly divisible triangular number I am just a beginner in C++ and I tried solving this problem:


  What is the first number of the form 1 + 2 + 3 + … + n that has over five hundred factors?


But it seems my code is not that efficient because its taking ages to find the answer:

#include&lt;iostream&gt;
using namespace std;

void triNum(int);

int main()
{
    int res=0;
    for (int i=1;i&lt;100000000;i++){
        res+=i;
        triNum(res);
    }
    cout&lt;&lt;endl;
}

void triNum(int n)
{
    int counter=0;
    for(int i=1;i&lt;=n;i++){
        if(n%i==0){
            counter+=1;
        }
    }
    if(counter==500){
        cout&lt;&lt;n;
    }
}
The program is slow for several reasons:


The triNum function finds all the divisors. It doesn't need to. After you find 500 divisors, you could print the number and return from the function


The function doesn't do what the problem description asked: it prints a number only when it has exactly 500 divisors, but the problem asks for the first number with over 500 divisors. If the first number has 502 divisors 
that would be a valid answer but your program will never print that.

Even after finding a number with over 500 divisors, your program would continue running until it checks 100000000 numbers. That's completely unnecessary, it should exit after finding the first appropriate number.
The program doesn't reuse the counts it already calculated. For example, after counting the divisors of 100, that could be reused when counting the divisors of 200. You could greatly benefit from using a map to cache already calculated counts.


The program has several other violations of good practices:


using namespace std is considered bad practice
The expression int i=1;i&lt;100000000;i++ is too compact, it's recommended to put spaces around operators and after semicolons, like this: int i = 1; i &lt; 100000000; i++
triNum is a poor name: it fails to describe what the function does
100000000 and 500 are magic numbers. It would be better to put these values in constants with descriptive names