Nyoj-quick search for prime numbers

Source: Internet
Author: User
Quick Search prime time limit: 1000 MS | memory limit: 65535 kb difficulty: 3
Description
Now I want to give you a positive integer N, which requires you to quickly find all the prime numbers in the numbers 2... n.
Input
Returns a positive integer n (n <= 2000000)
However, when n is 0, the program is terminated.
Test data cannot exceed 100 groups
Output
2 ~ Output of all prime numbers in the N range. Separate Two numbers with spaces
Sample Input
510110
Sample output
2 3 52 3 5 72 3 5 7 11
Source

Classic question


Code:

#include<stdio.h>#define MAX 2000100int f[MAX]={1,1};void g(){int i,j;for(i=2;i*i<MAX;++i){for(j=2;j<i;++j)if(i%j==0)break;if(j==i){f[i]=0;for(j=i*i;j<MAX;j+=i)f[j]=1;}elsef[i]=1;}}int main(){g();int N,i;while(scanf("%d",&N),N){printf("2");for(i=3;i<=N;++i)if(!f[i])printf(" %d",i);printf("\n");}return 0;}

Nyoj-quick search for prime numbers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.