Sum of prime numbers

Source: Internet
Author: User

Topic one, the sum of prime numbers

Describe

Now give you n number (0<n<1000), now ask you to write a program, find out the n number of all primes, and sum.

Input

The first line gives an integer n, which represents the number of test data. The next n number is the data to be tested, with each number less than 1000

Output

Each set of test data results in a row, outputting all the prime numbers of the test data given and

Sample input

5

1 2 3) 4 5

8

11 12 13 14 15 16 17 18

10

21 22 23 24 25 26 27 28 29 30

15

12 34 55 34 109 987 23 44 33 12 434 555 344 779 101

20

999 976 977 773 373 374 23 45 56 789 123 234 55 34 23 23 545 547 23 888

Sample output

10

41

52

233

2762

Problem Solving Ideas:

The maximum value of the input number is known by test instructions +within, so availableintThe usual practice of storing and judging prime numbers is from1start and target counting, so time complexity isO (n), however, by the nature of the remainder we know, if2~n-1among the existingNmay be set toK,bothn% k = = 0,Then byK * (n/k) = = NKnow thatn/kis alsoNan approximate, andkwith then/kmeet a greater thansqrt (n),a less thansqrt (n),so you just have to judgeNcan be2,3,......,sqrt (n)divisible, you can judgeNIs the prime number, the time complexity is fromO (n) descend toO (sqrt (n)).

The code is as follows:

1#include <cstdio>2 #defineMAXN 1010;3 BOOLIsPrime (intN) {//determine if it is a prime number4     if(N <=1)return false;//do not judge 0 and negative numbers5      for(inti =2; I * I <= N; i++) {6 //Traverse 2~SQRT (n), which can only be set if n is not close to the upper bound of int7         if(n% i = =0)return false;8     }9     return true;Ten } One  A intMain () { -     intA; -     intAns =0; the     intN; -     inti =0; -scanf"%d", &n); -      while(n--) { +scanf"%d", &a); -         if(IsPrime (a)) ans + =A; +     } Aprintf"%d\n", ans); at     return 0; -}

Sum of 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.