Sunday, August 2, 2009

Write a c++ program to print the list of prime numbers from 1-100?

#include %26lt;iostream%26gt;





using namespace std;








bool isprime(int j)


{


int k;


for (k=2; k %26lt;= j/2; k++)


{


if (!(j%k))


return false;


}


return true;


}





int main()


{


int i;


cout%26lt;%26lt;"Prime Numbers\n";


for (i=1; i%26lt;=100;i++)


{


if(isprime(i))cout%26lt;%26lt;i%26lt;%26lt;endl;


}


}

Write a c++ program to print the list of prime numbers from 1-100?
Well, here's the easiest way to do it! :D








#include %26lt;iostream%26gt;





void main()


{


cout %26lt;%26lt; "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,"


%26lt;%26lt;" 43, 47, 53, 59, 61, 67, 71, 73, 79,"


%26lt;%26lt;" 83, 89, 97"%26lt;%26lt;endl;


}
Reply:This program works much faster, but uses much more memory





#include%26lt;stdio.h%26gt;


void print_primes ( int inMax )


{


int * n = new int [ inMax ];


int i;


for(i=0;i%26lt;inMax;i++) n[i]=1; // consider all the numbers prime


for(i=2;i%26lt;=inMax;i++)


{


if(n[i-1]) // i is prime


{


// throw away all the numbers divisible by i


for(int j=i*2;j%26lt;=inMax;j+=i)


{


n[j-1] = 0;


}


}


}


// ok, print out results


puts("Prime numbers:");


for(i=0;i%26lt;inMax;i++)


{


if(n[i])


{


printf("%d ",i+1);


}


}


delete [] n;


}


int main(void)


{


print_primes(100);


}
Reply:the above will work but you don't need to test up to the number divided by 2 you only need to test up to the square root of the number. for example 81 you would never get to 40 you would bail out at 9 which is the square root of 81 and 79 which is prime you don't need to go to 39 you know after the number 8 that it is prime!


No comments:

Post a Comment