I have a prime number calculator program that uses type casting. The type casting occurs in my "prime_calculator" function, under "Discard remaining composite numbers".
If I run it without type casting it, I get an error msg "conversion from double to unsigned long; possible loss of data".
I was just wondering where/what is the "double"?
mw
Code:#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<malloc.h>
/*
This program calculates prime numbers using the Eratosthenes Sieve algorithm. It will find the prime numbers between 2 & "max". It overwrites the prime numbers to the file "prime_numbers.txt"
in the same folder.
Definitions:
1) Prime Number: a number with only 2 divisibles (itself & 1); the number "1" is not considered a prime number in this program
2) Composite Number: a number with more than 2 divisibles
Variable key:
discard = this is used to calculate composite numbers
count = a variable I use to count with
prime[max] = a pointer array that stores all of the numbers in the "max" range
max = the maximum range of prime numbers to calculate
highest = input from the user that is passed to "max"
An in-depth explanation of the Eratosthenes Sieve can be found on the internet.
*/
//prototypes
void start (void);
void prime_calculator (unsigned long max);
int main (void)
{
start ();
return 0;
}
void start (void)
{
unsigned long highest;
do
{
//input from user
printf ("\nType '0' to quit.");
printf ("\n\nPlease specify a max range to calculate prime numbers (up to 9000011).\n");
scanf ("%d", &highest);
//check input from user
if (highest < 0 || highest == 1 || highest > 9000011)
{
printf ("\n(Setting max range to 100)\n\n");
highest = 100;
}
//if user doesn't enter zero, call prime_calculator
if (highest != 0)
{
prime_calculator (highest);
}
} while (highest != 0);
}
void prime_calculator (unsigned long max)
{
unsigned long discard;
unsigned long count;
//Open & overwrite file for output
FILE *fp = fopen ("prime_numbers.txt", "w");
//Initialize the array
int *prime = malloc ((max+1)*sizeof(*prime));
if (!prime)
{
puts ("\n\nERROR! Not enough Memory!\n\n");
exit (1);
}
//initialize prime[max]
for (count = 0; count <= max; count++)
{
prime[count] = 1;
}
count = 0;
printf ("\nFinished initializing array.");
//Discard even composite numbers
for (discard = 4; discard <= max; discard = discard + 2)
{
prime[discard] = 0;
}
discard = 0;
printf ("\n\nFinished even discards.");
//Discard remaining composite numbers
count = 3;
do
{
for (discard = (int) pow(count,2); discard <= max; discard = discard + count * 2)
{
if (prime[discard] > 0)
{
prime[discard] = 0;
}
}
count++;
} while (pow(count,2) <= max);
count = 0;
discard = 0;
printf ("\n\nFinished all other discards.");
//Output
printf ("\n\nPrime Numbers between 2 and %d...\n", max);
for (count = 2; count <= max; count++)
{
if (prime[count] == 1)
{
printf ("%d ", count);
fprintf (fp,"\t%d", count);
}
}
count = 0;
fclose (fp);
free (prime);
printf ("\n\n");
}