Hello Team (Hellow World?),
I am a new C learner, I am trying to learn the language on my own, which it does not look too bad with the tutorials on this site.
I wrote a simple program to determine the primality of a number.
I wanted to extend my program to handle very large numbers.
Sure I can go on the web and find a number of routines already written, but I will not learn.
I want to modify the program, which I will list below, to:
- Handle very large numbers with millions of digits
- Use pointers to create a list of prime numbers as the program finds them
Also, could you please take a look at my simple program and criticize it? I really want to learn the language!
Thank you
/* This program will check a number for primality */
/* It expects 1 argument, an integer, positive number greater than 1 */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int check4prime(int p); /* Prototype function */
int main(int argc, char *argv[])
{
int n;
if (argc != 2) exit(EXIT_FAILURE); /* Need at least 2 args */
sscanf(argv[1], "%d", &n); /* Convert String to int */
if ( check4prime(n) ) /* if 1 is returned, we found a prime */
{
/* It is prime */
printf("%d is prime!\n", n);
exit(EXIT_SUCCESS);
} /* End if */
} /* End of main */
/* ################################### */
/* Function to check for primality */
/* ################################### */
int check4prime(int p)
{
if ( p <= 1 ) return 0; /* Prime can't be <= 1 */
if ( p == 2 || p == 3 ) return 1; /* first 2 prime numbers */
int rem = p % 2; /* No even #, except 2, is known to be prime */
if ( rem == 0) return 0; /* Eliminate even # first */
/* If we are here, that means the number is odd and it is neither 2 nor 3 */
/* Can it be prime? */
/* All known primes => 5, when divided by 6 have remainder of 1 or 5 */
rem = p % 6; /* Possible prime have rem = 1 or 5 */
if ( rem == 1 || rem == 5 ) /* Possible prime? */
{
/* So far, so good */
/* Continue checking for primality */
int k;
int sr = sqrt(p); /* No need to check behind sqrt(p) */
for ( k = 2; k <= sr; k++ ) {
if ( p % k == 0 )
{
return 0; /* False */
}
} /* for */
return 1; /* True, found a prime */
}
return 0; /* True, found a prime */
} /* End of check4prime */