2 solutions

  • 0
    @ 2023-10-28 13:08:55
    #include<iostream>
    using namespace std;
    int Judge(int n){
      /*if(n==1){
        return 0;
      }
      else*/
      //省去无效计算
      for(int i=2;i*i<=n;i++){
        if(n%i==0){
          return 0;
        }
      }
      return 1;
    }
    int main(){
      int n,sum=0;
      cin>>n;
      for(int i=2;i<=n;i++){
        sum+=Judge(i);
      }
      cout<<sum;
      return 0;
    }
    
    • 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;
      }
      
      • 1

      Information

      ID
      6767
      Time
      1000ms
      Memory
      256MiB
      Difficulty
      7
      Tags
      # Submissions
      307
      Accepted
      67
      Uploaded By