Find numbers between 1 and 10000 whose sum of digits are prime I have the following C code that finds numbers between 1 and 10000 whose sum of digits are prime and save then to a file.

#include&lt;stdio.h&gt;
#include&lt;conio.h&gt;
int sum_of_digits(int);
int check_prime(int);
void save_to_file(int);

int main()
{
    int i, num, isPrime;
    for(i=2; i&lt;=10000; i++)
    {
        num = sum_of_digits(i);
        isPrime = check_prime(num);
        if(isPrime)
        {
            printf("%d ", i);
            save_to_file(i);
        }
    }
    getch();
    return 0;
}

int sum_of_digits(int num)
{
    int sum = 0;
    while (num != 0)
    {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}

int check_prime(int num)
{
    int i;
    for (i=2; i&lt;=num-1; i++)
    {
        if (num%i == 0)
            return 0;
    }
    if (i == num)
        return 1;
}

void save_to_file(int num)
{
    FILE *fp;
    fp=fopen("prime.txt","a+");
    fprintf(fp, "%d ", num);
    fclose(fp);
}
The sum of the digits is such a small number (9+9+9+9=36 the maximum in your case) that you can even hard-code the values which are prime or not:

//number:         1  2  3  4  5  6  7
char isPrime[] = {0, 1, 1, 0, 1, 0, 1, ...}


But lets assume you don't go that far. The next best thing would be to generate such an array at run-time before your main loop (also based on the fact that the largest number you need to check if it's a prime is very small). A popular method for doing this is the Sieve of Eratosthenes.

Thus, you can now look up if the sum of the various digits is a prime or not in constant time: 

if (isPrime[sum_of_digits(i)])
{
    //...
}


As to writing the results to a file, I would keep the file open for the duration of the loop. This improves efficiency by sending bigger chunks of data to the disk thanks to buffering.