All prime numbers within billion (go language version)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

People who understand the elementary number theory know a simple way to determine the prime number:

Set n>1 as an integer, M is an integer, and n≤m<n^2, if all primes less than n are not factors of M, then M is prime.

From this proposition, you can write a very short procedure that iterates through all primes within billions.

package mainimport  (     "FMT") var _primes []uint64 = [] Uint64{    2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ,     31, 37, 41, 43, 47, 53, 59, 61, 67, 71,     73, 79, 83, 89, 97,}var _n intfunc main ()  {     _calcprimes ()     fmt. Println (_primes)     fmt. Println (100000000,  "The number of primes is",  _n)}func _calcprimes ()  {    n :=  len (_primes)     i := 0    for n :=  UInt64 (101); n < 10000; n += 2 {         for i = 1; i < n; i++ { // i starting from 1, because 2 must not divide N             if n%_primes[i] == 0 {                 break             }        }         if i == N {             _primes = append (_primes, n)          }    }    n = len (_primes)     for  n := uint64 (10001); n < 100000000; n += 2 {         for i = 1; i < N; i++ {             if n%_primes[i] == 0 {                 break             }        }         if i == N {             _primes = append (_primes, n)          }    }    n = len (_primes)     _N  = n}

The idea of a program is extremely simple. The first list of all the prime numbers within 100, using the 25 primes to get all the primes, and each to get a prime number, it is added to the back of the _primes, and then get all the prime number within billion.

My computer cannot be fully displayed because the array is too large. But the number is no problem. Is 5761455.

The Math software Mathematica verifies that the results are correct.













Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.