Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I check if a number is prime or not with the following code( of course using sqrt ):</p> <pre><code>bool IsPrime(const unsigned int x) { const unsigned int TOP = static_cast&lt;int&gt;( std::sqrt( static_cast&lt;double&gt;( x ) ) ) + 1; for ( int i=2; i != TOP; ++i ) { if (x % i == 0) return false; } return true; } </code></pre> <p>I use this method to determine the primes:</p> <pre><code>#include &lt;iostream&gt; using std::cout; using std::cin; using std::endl; #include &lt;cmath&gt; void initialize( unsigned int *, const unsigned int ); void show_list( const unsigned int *, const unsigned int ); void criba( unsigned int *, const unsigned int ); void setItem ( unsigned int *, const unsigned int, const unsigned int ); bool IsPrime(const unsigned int x) { const unsigned int TOP = static_cast&lt;int&gt;( std::sqrt( static_cast&lt;double&gt;( x ) ) ) + 1; for ( int i=2; i != TOP; ++i ) { if (x % i == 0) return false; } return true; } int main() { unsigned int *l; unsigned int n; cout &lt;&lt; "Ingrese tope de criba" &lt;&lt; endl; cin &gt;&gt; n; l = new unsigned int[n]; initialize( l, n ); cout &lt;&lt; "Esta es la lista" &lt;&lt; endl; show_list( l, n ); criba( l, n ); cout &lt;&lt; "Estos son los primos" &lt;&lt; endl; show_list( l, n ); } void initialize( unsigned int *l, const unsigned int n) { for( int i = 0; i &lt; n - 1; i++ ) *( l + i ) = i + 2; } void show_list( const unsigned int *l, const unsigned int n) { for( int i = 0; i &lt; n - 1; i++ ) { if( *( l + i ) != 0) cout &lt;&lt; l[i] &lt;&lt; " - "; } cout &lt;&lt; endl; } void setItem( unsigned int *l, const unsigned int n, const unsigned int p) { unsigned int i = 2; while( p * i &lt;= n) { *( l + (i * p - 2) ) = 0; i++; } } void criba( unsigned int *l, const unsigned int n) { for( int i = 0; i * i &lt;= n ; i++ ) if( IsPrime ( *( l + i) ) ) setItem( l, n, *(l + i) ); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload