Advertisement
banovski

Project Euler, Problem #7, C

Dec 20th, 2021 (edited)
1,186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 KB | None | 0 0
  1. /* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
  2.  * can see that the 6th prime is 13. What is the 10 001st prime
  3.  * number? */
  4.  
  5. /* Solution #1: a basic one */
  6.  
  7. #include <stdio.h>
  8.  
  9. int main()
  10. {
  11.      short int number_of_primes = 3;
  12.      char is_prime;
  13.      long int current_number = 4;
  14.      long int i, current_prime;
  15.  
  16.      while(number_of_primes <= 10001)
  17.      {
  18.           is_prime = 1;
  19.           for(i = 2; i <= current_number / 2; i++)
  20.                if(current_number % i == 0)
  21.                {
  22.                     is_prime = 0;
  23.                     break;
  24.                }
  25.  
  26.           if(is_prime == 1)
  27.           {
  28.                current_prime = current_number;
  29.                number_of_primes++;
  30.           }
  31.          
  32.           current_number++;
  33.      }
  34.      printf("%ld\n", current_prime);
  35.      return(0);
  36. }
  37.  
  38. /* 104743 */
  39.  
  40. /* real 0m5,833s
  41.  * user 0m5,829s
  42.  * sys  0m0,000s */
  43.  
  44. /* ########################################################### */
  45. /* Solution #2: a more efficient one: numbers are checked against
  46.  * items of an array with previously found primes. */
  47.  
  48. #include <stdio.h>
  49. # define TN 10001
  50.  
  51. int main()
  52.  
  53. {
  54.      long int primes[TN] = {2};
  55.      short int primes_number = 1;
  56.      short int i;
  57.      long int checked_number = 3;
  58.      char is_prime;
  59.  
  60.      while(primes_number < TN)
  61.      {
  62.           is_prime = 1;
  63.           for(i = 0; i < primes_number; i++)
  64.                if(checked_number % primes[i] == 0)
  65.                {
  66.                     is_prime = 0;
  67.                     break;
  68.                }
  69.  
  70.           if(is_prime == 1)
  71.           {
  72.                primes[primes_number] = checked_number;
  73.                primes_number++;
  74.           }
  75.          
  76.           checked_number++;
  77.      }
  78.      printf("%ld\n", primes[primes_number - 1]);
  79.      return(0);
  80. }
  81.  
  82. /* 104743 */
  83.  
  84. /* real 0m1,189s
  85.  * user 0m1,187s
  86.  * sys  0m0,000s */
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement