Given a positive integer N, please list all prime numbers from 2 to P, where P is the largest prime number less than or equal to N. N ranges from 1 to 1000. A prime number is defined as an integer greater than 1 that has no positive divisors other than 1 and itself. Each line in the output can contain only five numbers, as shown in the example output.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
EOF inputs: each test case consists of a single line containing a positive integer N (1 ≤ N ≤ 1000). | In the output, each line can contain at most five numbers, as shown in the example output. (Each number includes ten characters of leading whitespace.) |
50 | 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 |
Thought Process
Use a for loop to determine prime numbers from 2 to N. Calculate the length of the string, output "10 - length of the string" whitespace characters, and then output the number.
Keep track of the current number of output numbers. Increment this variable by 1 each time a number is output. When this variable reaches 5, insert a newline and reset the variable to zero.
After each set of data, print an extra new line.
Sample Code-ZeroJudge A626: Prime Directive
#include <iostream>
#include <math.h>
#include <map>
using namespace std;
int current = 0;
map<int, string>MAP;
void out(string num)
{
cout << MAP[int(10 - num.length())] << num;
current++;
if (current == 5)
{
cout << "\n";
current = 0;
}
}
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
MAP[9] = " ";
MAP[8] = " ";
MAP[7] = " ";
MAP[6] = " ";
int N;
while (cin >> N)
{
current = 0;
for (int i = 2; i<=N; i++)
{
bool isPrime = true;
for (int j = 2; j<int(sqrt(i)+1); j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
out(to_string(i));
}
}
cout << "\n";
}
}
//ZeroJudge A626
//Dr. SeanXD