Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
- * can see that the 6th prime is 13. What is the 10 001st prime
- * number? */
- /* Solution #1: a basic one */
- #include <stdio.h>
- int main()
- {
- short int number_of_primes = 3;
- char is_prime;
- long int current_number = 4;
- long int i, current_prime;
- while(number_of_primes <= 10001)
- {
- is_prime = 1;
- for(i = 2; i <= current_number / 2; i++)
- if(current_number % i == 0)
- {
- is_prime = 0;
- break;
- }
- if(is_prime == 1)
- {
- current_prime = current_number;
- number_of_primes++;
- }
- current_number++;
- }
- printf("%ld\n", current_prime);
- return(0);
- }
- /* 104743 */
- /* real 0m5,833s
- * user 0m5,829s
- * sys 0m0,000s */
- /* ########################################################### */
- /* Solution #2: a more efficient one: numbers are checked against
- * items of an array with previously found primes. */
- #include <stdio.h>
- # define TN 10001
- int main()
- {
- long int primes[TN] = {2};
- short int primes_number = 1;
- short int i;
- long int checked_number = 3;
- char is_prime;
- while(primes_number < TN)
- {
- is_prime = 1;
- for(i = 0; i < primes_number; i++)
- if(checked_number % primes[i] == 0)
- {
- is_prime = 0;
- break;
- }
- if(is_prime == 1)
- {
- primes[primes_number] = checked_number;
- primes_number++;
- }
- checked_number++;
- }
- printf("%ld\n", primes[primes_number - 1]);
- return(0);
- }
- /* 104743 */
- /* real 0m1,189s
- * user 0m1,187s
- * sys 0m0,000s */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement