P5723 Pocket of Prime
Description
Little A has a pocket of primes, where can includes any prime. He always starts at 2 and enumerates if it's a prime. If it's, he will put this number into the pocket. But the load capability of the pocket is the sum of the numbers. The pocket's capability is limited; it cannot load the prime after the sum of primes over L(1<=L<=100000). After given L, asks how many primes can the pocket take? You need to output these primes from small to large and output the capability; there are lines between numbers.
Input format
None
Output format
None
Example
Input
100
Output
2
3
5
7
11
13
17
19
23
9
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Code
#include<iostream>
#include<cstring>
using namespace std;
int prime(){
int n;
int c = 0;
cin >> n;
int tmp = n;
bool a[n+1];
memset(a,true,sizeof(a));
for(int i=2;i*i<=n;i++){
if(a[i]==true){
for(int p=i*i;p<=n;p+=i){
a[p]=false;
}
}
}
for(int i=2;i<=n;i++){
if(a[i]==true){
tmp -= i;
if(tmp<0)
break;
c++;
cout << i << endl;
}
}
cout << c << endl;
return 0;
}
What I learned?
The algorithm to sift prime.
Sieve of Eratosthenes
// C++ program to print all primes smaller than or equal to
// n using Sieve of Eratosthenes
#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
bool prime[n+1];
memset(prime, true, sizeof(prime));
for (int p=2; p*p<=n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p greater than or
// equal to the square of it
// numbers which are multiple of p and are
// less than p^2 are already been marked.
for (int i=p*p; i<=n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int p=2; p<=n; p++)
if (prime[p])
cout << p << " ";
}
// Driver Program to test above function
int main()
{
int n = 30;
cout << "Following are the prime numbers smaller "
<< " than or equal to " << n << endl;
SieveOfEratosthenes(n);
return 0;
}
Why pp<=n?
The minimum prime factor of a number n must be less than the root n.
Mathematical expression: ab=n, if a<root n, b must > root n.

浙公网安备 33010602011771号