code_junkie

Prime number calculation fun

Nov 12th, 2011
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.10 KB | None | 0 0
  1. public class Primes {
  2.  
  3. public static void main(String[] args) {
  4. int topPrime = 150000;
  5. int current = 2;
  6. int count = 0;
  7. int lastPrime = 2;
  8.  
  9. long start = System.currentTimeMillis();
  10.  
  11. while (count < topPrime) {
  12.  
  13. boolean prime = true;
  14.  
  15. int top = (int)Math.sqrt(current) + 1;
  16.  
  17. for (int i = 2; i < top; i++) {
  18. if (current % i == 0) {
  19. prime = false;
  20. break;
  21. }
  22. }
  23.  
  24. if (prime) {
  25. count++;
  26. lastPrime = current;
  27. }
  28. if (current == 2) {
  29. current++;
  30. } else {
  31. current = current + 2;
  32. }
  33. }
  34.  
  35. System.out.println("Last prime = " + lastPrime);
  36. System.out.println("Total time = " + (double)(System.currentTimeMillis() - start) / 1000);
  37. }
  38. }
  39.  
  40. int count = 0;
  41. ...
  42. for (int i = 2; i < top; i++)
  43. ...
  44. if (current == 2)
  45. current++;
  46. else
  47. current += 2;
  48.  
  49. int count = 1;
  50. ...
  51. for (int i = 3; i < top; i += 2)
  52. ...
  53. current += 2;
  54.  
  55. int count = 1;
  56. ...
  57. for (int i = 3; i*i <= current; i += 2)
  58. ...
  59. current += 2;
  60.  
  61. #!/usr/bin/env python
  62. def iprimes_upto(limit):
  63. """Generate all prime numbers less then limit.
  64.  
  65. http://stackoverflow.com/questions/188425/project-euler-problem#193605
  66. """
  67. is_prime = [True] * limit
  68. for n in range(2, limit):
  69. if is_prime[n]:
  70. yield n
  71. for i in range(n*n, limit, n): # start at ``n`` squared
  72. is_prime[i] = False
  73.  
  74. def sup_prime(n):
  75. """Return an integer upper bound for p(n).
  76.  
  77. p(n) < n (log n + log log n - 1 + 1.8 log log n / log n)
  78.  
  79. where p(n) is the n-th prime.
  80. http://primes.utm.edu/howmany.shtml#2
  81. """
  82. from math import ceil, log
  83. assert n >= 13
  84. pn = n * (log(n) + log(log(n)) - 1 + 1.8 * log(log(n)) / log(n))
  85. return int(ceil(pn))
  86.  
  87. if __name__ == '__main__':
  88. import sys
  89. max_number_of_primes = int(sys.argv[1]) if len(sys.argv) == 2 else 150000
  90. primes = list(iprimes_upto(sup_prime(max_number_of_primes)))
  91. print("Generated %d primes" % len(primes))
  92. n = 100
  93. print("The first %d primes are %s" % (n, primes[:n]))
  94.  
  95. $ python primes.py
  96.  
  97. Generated 153465 primes
  98. The first 100 primes are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
  99. 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
  100. 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,
  101. 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
  102. 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,
  103. 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
  104. 467, 479, 487, 491, 499, 503, 509, 521, 523, 541]
  105.  
  106. class Program
  107. {
  108. static void Main(string[] args)
  109. {
  110. int count = 0;
  111. int max = 150000;
  112. int i = 2;
  113.  
  114. DateTime start = DateTime.Now;
  115. while (count < max)
  116. {
  117. if (IsPrime(i))
  118. {
  119. count++;
  120. }
  121.  
  122. i++;
  123.  
  124. }
  125. DateTime end = DateTime.Now;
  126.  
  127. Console.WriteLine("Total time taken: " + (end - start).TotalSeconds.ToString() + " seconds");
  128. Console.ReadLine();
  129. }
  130.  
  131. static bool IsPrime(int n)
  132. {
  133. if (n < 4)
  134. return true;
  135. if (n % 2 == 0)
  136. return false;
  137.  
  138. int s = (int)Math.Sqrt(n);
  139. for (int i = 2; i <= s; i++)
  140. if (n % i == 0)
  141. return false;
  142.  
  143. return true;
  144. }
  145. }
  146.  
  147. while (count < topPrime) {
  148.  
  149. boolean prime = true;
  150.  
  151. boolean prime;
  152. while (count < topPrime) {
  153.  
  154. prime = true;
  155.  
  156. class Program
  157. {
  158. static void Main(string[] args)
  159. {
  160. DateTime start = DateTime.Now;
  161.  
  162. int count = 2; //once 2 and 3
  163.  
  164. int i = 5;
  165. while (count < 150000)
  166. {
  167. if (IsPrime(i))
  168. {
  169. count++;
  170. }
  171.  
  172. i += 2;
  173.  
  174. if (IsPrime(i))
  175. {
  176. count++;
  177. }
  178.  
  179. i += 4;
  180. }
  181.  
  182. DateTime end = DateTime.Now;
  183.  
  184. Console.WriteLine("Total time taken: " + (end - start).TotalSeconds.ToString() + " seconds");
  185. Console.ReadLine();
  186. }
  187.  
  188. static bool IsPrime(int n)
  189. {
  190. //if (n < 4)
  191. //return true;
  192. //if (n % 2 == 0)
  193. //return false;
  194.  
  195. int s = (int)Math.Sqrt(n);
  196. for (int i = 2; i <= s; i++)
  197. if (n % i == 0)
  198. return false;
  199.  
  200. return true;
  201. }
  202. }
  203.  
  204. public class Primes
  205. {
  206. // Original code
  207. public static void first()
  208. {
  209. int topPrime = 150003;
  210. int current = 2;
  211. int count = 0;
  212. int lastPrime = 2;
  213.  
  214. long start = System.currentTimeMillis();
  215.  
  216. while (count < topPrime) {
  217.  
  218. boolean prime = true;
  219.  
  220. int top = (int)Math.sqrt(current) + 1;
  221.  
  222. for (int i = 2; i < top; i++) {
  223. if (current % i == 0) {
  224. prime = false;
  225. break;
  226. }
  227. }
  228.  
  229. if (prime) {
  230. count++;
  231. lastPrime = current;
  232. // System.out.print(lastPrime + " "); // Checking algo is correct...
  233. }
  234. if (current == 2) {
  235. current++;
  236. } else {
  237. current = current + 2;
  238. }
  239. }
  240.  
  241. System.out.println("n-- First");
  242. System.out.println("Last prime = " + lastPrime);
  243. System.out.println("Total time = " + (double)(System.currentTimeMillis() - start) / 1000);
  244. }
  245.  
  246. // My attempt
  247. public static void second()
  248. {
  249. final int wantedPrimeNb = 150000;
  250. int count = 0;
  251.  
  252. int currentNumber = 1;
  253. int increment = 4;
  254. int lastPrime = 0;
  255.  
  256. long start = System.currentTimeMillis();
  257.  
  258. NEXT_TESTING_NUMBER:
  259. while (count < wantedPrimeNb)
  260. {
  261. currentNumber += increment;
  262. increment = 6 - increment;
  263. if (currentNumber % 2 == 0) // Even number
  264. continue;
  265. if (currentNumber % 3 == 0) // Multiple of three
  266. continue;
  267.  
  268. int top = (int) Math.sqrt(currentNumber) + 1;
  269. int testingNumber = 5;
  270. int testIncrement = 2;
  271. do
  272. {
  273. if (currentNumber % testingNumber == 0)
  274. {
  275. continue NEXT_TESTING_NUMBER;
  276. }
  277. testingNumber += testIncrement;
  278. testIncrement = 6 - testIncrement;
  279. } while (testingNumber < top);
  280. // If we got there, we have a prime
  281. count++;
  282. lastPrime = currentNumber;
  283. // System.out.print(lastPrime + " "); // Checking algo is correct...
  284. }
  285.  
  286. System.out.println("n-- Second");
  287. System.out.println("Last prime = " + lastPrime);
  288. System.out.println("Total time = " + (double) (System.currentTimeMillis() - start) / 1000);
  289. }
  290.  
  291. public static void main(String[] args)
  292. {
  293. first();
  294. second();
  295. }
  296. }
  297.  
  298. if (current != 2 && current % 2 == 0)
  299. prime = false;
  300. else {
  301. for (int i = 3; i < top; i+=2) {
  302. if (current % i == 0) {
  303. prime = false;
  304. break;
  305. }
  306. }
  307. }
  308.  
  309. let max = 150000
  310. let numbers = [2..max]
  311. let rec getPrimes sieve max =
  312. match sieve with
  313. | [] -> sieve
  314. | _ when sqrt(float(max)) < float sieve.[0] -> sieve
  315. | _ -> let prime = sieve.[0]
  316. let filtered = List.filter(fun x -> x % prime <> 0) sieve // Removes the prime as well so the recursion works correctly.
  317. let result = getPrimes filtered max
  318. prime::result // The filter removes the prime so add it back to the primes result.
  319.  
  320. let timer = System.Diagnostics.Stopwatch()
  321. timer.Start()
  322. let r = getPrimes numbers max
  323. timer.Stop()
  324. printfn "Primes: %A" r
  325. printfn "Elapsed: %d.%d" timer.Elapsed.Seconds timer.Elapsed.Milliseconds
  326.  
  327. #include<stdio.h>
  328. #include<math.h>
  329. #include<stdlib.h>
  330. #include<time.h>
  331.  
  332. //5MB... allocate a lot of memory at once each time we need it
  333. #define ARRAYMULT 5242880
  334.  
  335.  
  336. //list of calculated primes
  337. __int64* primes;
  338. //number of primes calculated
  339. __int64 primeCount;
  340. //the current size of the array
  341. __int64 arraySize;
  342.  
  343. //Prints all of the calculated primes
  344. void PrintPrimes()
  345. {
  346. __int64 i;
  347. for(i=0; i<primeCount; i++)
  348. {
  349. printf("%d ", primes[i]);
  350. }
  351.  
  352. }
  353.  
  354. //Calculates all prime numbers to max
  355. void CalcPrime(__int64 max)
  356. {
  357. register __int64 i;
  358. double square;
  359. primes = (__int64*)malloc(sizeof(__int64) * ARRAYMULT);
  360. primeCount = 0;
  361. arraySize = ARRAYMULT;
  362.  
  363. //we provide the first prime because its even, and it would be convenient to start
  364. //at an odd number so we can skip evens.
  365. primes[0] = 2;
  366. primeCount++;
  367.  
  368.  
  369.  
  370. for(i=3; i<max; i+=2)
  371. {
  372. int j;
  373. square = sqrt((double)i);
  374.  
  375. //only test the current candidate against other primes.
  376. for(j=0; j<primeCount; j++)
  377. {
  378. //prime divides evenly into candidate, so we have a non-prime
  379. if(i%primes[j]==0)
  380. break;
  381. else
  382. {
  383. //if we've reached the point where the next prime is > than the square of the
  384. //candidate, the candidate is a prime... so we can add it to the list
  385. if(primes[j] > square)
  386. {
  387. //our array has run out of room, so we need to expand it
  388. if(primeCount >= arraySize)
  389. {
  390. int k;
  391. __int64* newArray = (__int64*)malloc(sizeof(__int64) * (ARRAYMULT + arraySize));
  392.  
  393. for(k=0; k<primeCount; k++)
  394. {
  395. newArray[k] = primes[k];
  396. }
  397.  
  398. arraySize += ARRAYMULT;
  399. free(primes);
  400. primes = newArray;
  401. }
  402. //add the prime to the list
  403. primes[primeCount] = i;
  404. primeCount++;
  405. break;
  406.  
  407. }
  408. }
  409.  
  410. }
  411.  
  412. }
  413.  
  414.  
  415. }
  416. int main()
  417. {
  418. int max;
  419. time_t t1,t2;
  420. double elapsedTime;
  421.  
  422. printf("Enter the max number to calculate primes for:n");
  423. scanf_s("%d",&max);
  424. t1 = time(0);
  425. CalcPrime(max);
  426. t2 = time(0);
  427. elapsedTime = difftime(t2, t1);
  428. printf("%d Primes found.n", primeCount);
  429. printf("%f seconds elapsed.nn",elapsedTime);
  430. //PrintPrimes();
  431. scanf("%d");
  432. return 1;
  433. }
  434.  
  435. /*Calculate the primes till TOTALPRIMES*/
  436. #include <stdio.h>
  437. #define TOTALPRIMES 15000
  438.  
  439. main(){
  440. int primes[TOTALPRIMES];
  441. int count;
  442. int i, j, cpr;
  443. char isPrime;
  444.  
  445. primes[0] = 2;
  446. count = 1;
  447.  
  448. for(i = 3; count < TOTALPRIMES; i+= 2){
  449. isPrime = 1;
  450.  
  451. //check divisiblity only with previous primes
  452. for(j = 0; j < count; j++){
  453. cpr = primes[j];
  454. if(i % cpr == 0){
  455. isPrime = 0;
  456. break;
  457. }
  458. if(cpr*cpr > i){
  459. break;
  460. }
  461. }
  462. if(isPrime == 1){
  463. //printf("Prime: %dn", i);
  464. primes[count] = i;
  465. count++;
  466. }
  467.  
  468.  
  469. }
  470.  
  471. printf("Last prime = %dn", primes[TOTALPRIMES - 1]);
  472. }
  473.  
  474. package demo;
  475.  
  476. import java.util.List;
  477. import java.util.HashSet;
  478.  
  479. class Primality
  480. {
  481. int current = 0;
  482. int minValue;
  483. private static final HashSet<Integer> resultSet = new HashSet<Integer>();
  484. final int increment = 2;
  485. // An obvious optimization is to use some already known work as an internal
  486. // constant table of some kind, reducing approaches to boundary conditions.
  487. int[] alreadyKown =
  488. {
  489. 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
  490. 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
  491. 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,
  492. 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
  493. 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,
  494. 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
  495. 467, 479, 487, 491, 499, 503, 509, 521, 523, 541
  496. };
  497. // Trivial constructor.
  498.  
  499. public Primality(int minValue)
  500. {
  501. this.minValue = minValue;
  502. }
  503. List calcPrimes( int startValue )
  504. {
  505. // eliminate several hundred already known primes
  506. // by hardcoding the first few dozen - implemented
  507. // from prior work by J.F. Sebastian
  508. if( startValue > this.minValue )
  509. {
  510. // Duh.
  511. current = Math.abs( start );
  512. do
  513. {
  514. boolean prime = true;
  515. int index = current;
  516. do
  517. {
  518. if(current % index == 0)
  519. {
  520. // here, current cannot be prime so break.
  521. prime = false;
  522. break;
  523. }
  524. while( --index > 0x00000000 );
  525.  
  526. // Unreachable if not prime
  527. // Here for clarity
  528.  
  529. if ( prime )
  530. {
  531. resultSet dot add ( or put or whatever it is )
  532. new Integer ( current ) ;
  533. }
  534. }
  535. while( ( current - increment ) > this.minValue );
  536. // Sanity check
  537. if resultSet dot size is greater that zero
  538. {
  539. for ( int anInt : alreadyKown ) { resultSet.add( new Integer ( anInt ) );}
  540. return resultSet;
  541. }
  542. else throw an exception ....
  543. }
  544.  
  545. package demo;
  546.  
  547. import java.util.List;
  548. import java.util.HashSet;
  549.  
  550. class Primality
  551. {
  552. int current = 0;
  553. int minValue;
  554. private static final HashSet<Integer> resultSet = new HashSet<Integer>();
  555. final int increment = 2;
  556. // An obvious optimization is to use some already known work as an internal
  557. // constant table of some kind, reducing approaches to boundary conditions.
  558. int[] alreadyKown =
  559. {
  560. 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
  561. 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
  562. 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,
  563. 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
  564. 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,
  565. 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
  566. 467, 479, 487, 491, 499, 503, 509, 521, 523, 541
  567. };
  568. // Trivial constructor.
  569.  
  570. public Primality(int minValue)
  571. {
  572. this.minValue = minValue;
  573. }
  574. List calcPrimes( int startValue )
  575. {
  576. // eliminate several hundred already known primes
  577. // by hardcoding the first few dozen - implemented
  578. // from prior work by J.F. Sebastian
  579. if( startValue > this.minValue )
  580. {
  581. // Duh.
  582. current = Math.abs( start );
  583. do
  584. {
  585. boolean prime = true;
  586. int index = current;
  587. do
  588. {
  589. if(current % index == 0)
  590. {
  591. // here, current cannot be prime so break.
  592. prime = false;
  593. break;
  594. }
  595. while( --index > 0x00000000 );
  596.  
  597. // Unreachable if not prime
  598. // Here for clarity
  599.  
  600. if ( prime )
  601. {
  602. resultSet dot add ( or put or whatever it is )
  603. new Integer ( current ) ;
  604. }
  605. }
  606. while( ( current - increment ) > this.minValue );
  607. // Sanity check
  608. if resultSet dot size is greater that zero
  609. {
  610. for ( int anInt : alreadyKown ) { resultSet.add( new Integer ( anInt ) );}
  611. return resultSet;
  612. }
  613. else throw an exception ....
  614. }
  615.  
  616. if(current % 5 == 0 )
  617. if(current % 7 == 0 )
  618. if( ( ( ( current % 12 ) +1 ) == 0) || ( ( ( current % 12 ) -1 ) == 0) ){break;}
  619. if( ( ( ( current % 18 ) +1 ) == 0) || ( ( ( current % 18 ) -1 ) == 0) ){break;}
  620. if( ( ( ( current % 24 ) +1 ) == 0) || ( ( ( current % 24 ) -1 ) == 0) ){break;}
  621. if( ( ( ( current % 36 ) +1 ) == 0) || ( ( ( current % 36 ) -1 ) == 0) ){break;}
  622. if( ( ( ( current % 24 ) +1 ) == 0) || ( ( ( current % 42 ) -1 ) == 0) ){break;}
  623.  
  624.  
  625. // and - new work this morning:
  626.  
  627.  
  628. package demo;
  629.  
  630. /**
  631. *
  632. * Buncha stuff deleted for posting .... duh.
  633. *
  634. * @author Author
  635. * @version 0.2.1
  636. *
  637. * Note strings are base36
  638. */
  639. public final class Alice extends java.util.HashSet<java.lang.String>
  640. {
  641. // prints 14551 so it's 14 ½ seconds to get 40,000 likely primes
  642. // using Java built-in on amd sempron 1.8 ghz / 1600 mhz front side bus 256 k L-2
  643. public static void main(java.lang.String[] args)
  644. {
  645. try
  646. {
  647. final long start=System.currentTimeMillis();
  648. // VM exhibits spurious 16-bit pointer behaviour somewhere after 40,000
  649. final java.lang.Integer upperBound=new java.lang.Integer(40000);
  650. int index = upperBound.intValue();
  651.  
  652. final java.util.HashSet<java.lang.String>hashSet
  653. = new java.util.HashSet<java.lang.String>(upperBound.intValue());//
  654. // Arbitraily chosen value, based on no idea where to start.
  655. java.math.BigInteger probablePrime
  656. = new java.math.BigInteger(16,java.security.SecureRandom.getInstance("SHA1PRNG"));
  657. do
  658. {
  659. java.math.BigInteger nextProbablePrime = probablePrime.nextProbablePrime();
  660. if(hashSet.add(new java.lang.String(nextProbablePrime.toString(Character.MAX_RADIX))))
  661. {
  662. probablePrime = nextProbablePrime;
  663. if( ( index % 100 ) == 0x00000000 )
  664. {
  665. // System.out.println(nextProbablePrime.toString(Character.MAX_RADIX));//
  666. continue;
  667. }
  668. else
  669. {
  670. continue;
  671. }
  672. }
  673. else
  674. {
  675. throw new StackOverflowError(new String("hashSet.add(string) failed on iteration: "+
  676. Integer.toString(upperBound.intValue() - index)));
  677. }
  678. }
  679. while(--index > 0x00000000);
  680. System.err.println(Long.toString( System.currentTimeMillis() - start));
  681. }
  682. catch(java.security.NoSuchAlgorithmException nsae)
  683. {
  684. // Never happen
  685. return;
  686. }
  687. catch(java.lang.StackOverflowError soe)
  688. {
  689. // Might happen
  690. System.out.println(soe.getMessage());//
  691. return;
  692. }
  693. }
  694. }// end class Alice
  695.  
  696. //
  697. // Finds the n first prime numbers.
  698. //
  699. //count: Number of prime numbers to find.
  700. //listPrimes: A reference to a list that will contain all n first prime if getLast is set to false.
  701. //getLast: If true, the list will only contain the nth prime number.
  702. //
  703. static ulong GetPrimes(ulong count, ref IList listPrimes, bool getLast)
  704. {
  705. if (count == 0)
  706. return 0;
  707. if (count == 1)
  708. {
  709. if (listPrimes != null)
  710. {
  711. if (!getLast || (count == 1))
  712. listPrimes.Add(2);
  713. }
  714.  
  715. return count;
  716. }
  717.  
  718. ulong currentSquare = 1;
  719. ulong nextSquare = 9;
  720. ulong nextSquareIndex = 3;
  721. ulong primesCount = 1;
  722.  
  723. List dividers = new List();
  724.  
  725. //Only check for odd numbers starting with 3.
  726. for (ulong curNumber = 3; (curNumber (nextSquareIndex % div) == 0) == false)
  727. dividers.Add(nextSquareIndex);
  728.  
  729. //Move to next square number
  730. currentSquare = nextSquare;
  731.  
  732. //Skip the even dividers so take the next odd square number.
  733. nextSquare += (4 * (nextSquareIndex + 1));
  734. nextSquareIndex += 2;
  735.  
  736. //We may continue as a square number is never a prime number for obvious reasons :).
  737. continue;
  738. }
  739.  
  740. //Check if there is at least one divider for the current number.
  741. //If so, this is not a prime number.
  742. if (dividers.Exists(div => (curNumber % div) == 0) == false)
  743. {
  744. if (listPrimes != null)
  745. {
  746. //Unless we requested only the last prime, add it to the list of found prime numbers.
  747. if (!getLast || (primesCount + 1 == count))
  748. listPrimes.Add(curNumber);
  749. }
  750. primesCount++;
  751. }
  752. }
  753.  
  754. return primesCount;
  755. }
  756.  
  757. //returns number of primes less than n
  758. private static int getNumberOfPrimes(final int n)
  759. {
  760. if(n < 2)
  761. return 0;
  762. BitSet candidates = new BitSet(n - 1);
  763. candidates.set(0, false);
  764. candidates.set(1, false);
  765. candidates.set(2, n);
  766. for(int i = 2; i < n; i++)
  767. if(candidates.get(i))
  768. for(int j = i + i; j < n; j += i)
  769. if(candidates.get(j) && j % i == 0)
  770. candidates.set(j, false);
  771. return candidates.cardinality();
  772. }
Add Comment
Please, Sign In to add comment