2 solutions

  • 0
    @ 2023-10-3 10:02:31

    非函数解

    #include <stdio.h>  
    #include <stdbool.h>  
    
    int main() {  
    	int n;  
    	scanf("%d", &n);  
    	int count = 0;  
    	for (int i = 2; i <= n; i++) {  
    		bool is_prime = true; //int is_prime = 1;
    		for (int j = 2; j * j <= i; j++) {  
    			if (i % j == 0) {  
    				is_prime = false;  //is_prime = 0;
    				break;  
    			}  
    		}  
    		if (is_prime) {  // is_prime = 1;
    			count++;  
    		}  
    	}  
    	
    	printf("%d",count);  
    	return 0;  
    }
    

    函数解

    #include<bits/stdc++.h>
    using namespace std;
    const int N=1e6+5;
    int vis[N],prime[N],cnt;
    void get_prime(int k)
    {
    	vis[0]=vis[1]=1;
    	for(int i=2;i<=k;i++)
    	{
    		if(!vis[i])
    		{
    			prime[++cnt]=i;
    			for(int j=2*i;j<=k;j+=i)
    				vis[j]=1;
    		}
    	}
    }
    int main()
    {
    	int n;
    	cin>>n;
    	get_prime(n);
    	cout<<cnt;
    	return 0;
    }
    

    Information

    ID
    6767
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    8
    Tags
    # Submissions
    237
    Accepted
    45
    Uploaded By