Dec 16, 2011

Print specific primes


On primes have written several programs and I've noticed that teachers have some fixed programming with them. Well, today the program prints the number of prime numbers the user wants and is interesting because it is a good example of the usefulness of infinite loops , which we had seen before.
Ok, the code is this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 # Include <iostream>
 using namespace std;

 int main ()
 {
     int cnt, i = 0, ii, respectively, nc = 0, np = 0;
     court <<"Enter the amount of numbers:" cin>> cnt;
     for (;;)
     {
         + + i;
         for (i = 1 ii <= i, ii + +)
         {
             res = i% ii;
             if (res == 0)
                 nc = nc + 1;
         }
         if (nc == 2)
         {
             court <<i <<"";
             np + +;
         }
         nc = 0;
         if (np == cnt)
             break;
     }
 } 
If you have trouble understanding how we got the prime numbers should give you a review in these posts: Know if is prime or not and Cousins ​​in the range .
What we did is that the entire program was in an infinite loop will stop when our variable is incremented each time we get a prime number np is equal to the variable with the desired amount of prime numbers cnt.
But remember that we can use an infinite loop, it is much better while loop :
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 # Include <iostream>
 using namespace std;

 int main ()
 {
     int cnt, i = 0, ii, respectively, nc = 0, np = 0;
     court <<"Enter the amount of numbers:" cin>> cnt;
     while (np! = cnt)
     {
         i + +;
         for (i = 1 ii <= i ii + +)
         {
             res = i% ii;
             if (res == 0)
                 nc = nc + 1;
         }
         if (nc == 2)
         {
             court <<i <<"";
             np + +;
         }
         nc = 0;
     }
 } 
Only put the word while instead of for, copy the condition that 'condition' (yes, I know) the break and paste it inside the parentheses of the while but in a manner contrary (from == to! = Or <a> ).

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes