2018年1月12日 星期五

[MM36-易] Prime Numbers(C++)

[MM36-易] Prime Numbers

Problem Description
An integer n is said to be a prime number if it is greater than 1 and has only factors of 1 and itself. For example, 2, 3, 5, and7 are prime numbers, but 4, 6, 8 and 9 are not. This problem asks you to calculate the number of prime numbers less than a given integer N.
Technical Specification
2 ≤ N ≤ 30000
Input File Format
The input data consists of several lines, each line contains one integer 2 ≤ N ≤ 30000. The end of input is indicated by a number 0. There are at most 6 test cases.
Output Format
For each case, print the number of primenumbers less than N.
Example

Sample Input:Sample Output:
3
10
15
32
0
1
4
6
11

  1. #include <iostream>  
  2. #include <string>  
  3. #include <sstream>  
  4. #include <stdio.h>  
  5. #include <ctype.h>  
  6. #include <cmath>  
  7. using namespace std;  
  8.   
  9. int main() {  
  10.     // [MM36-易] Prime Numbers  
  11.     string Num;  
  12.     while(getline(cin, Num))  
  13.     {  
  14.         int num = stoi(Num);  
  15.         int count = 0;  
  16.         if(num != 0)  
  17.         {  
  18.             for(int i = 1;i < num;i++)  
  19.             {  
  20.                 int c = 0;  
  21.                 for(int j = 1;j <= i;j++)  
  22.                 {  
  23.                     if(i % j == 0)  
  24.                     {  
  25.                         c++;  
  26.                     }  
  27.                 }  
  28.                 if(c == 2 && num != 1)  
  29.                 {  
  30.                     count++;  
  31.                 }  
  32.             }  
  33.             cout << count << endl;  
  34.         }  
  35.         else  
  36.         {  
  37.             break;  
  38.         }  
  39.     }  
  40.     return 0;  
  41. }  

沒有留言:

張貼留言