[NYOJ] [1022] Sum of Primes Problem

Problem Description

Loading...

Problem Analysis

Used a prime sieve table

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<stdio.h>
int main() {
	int a[1500]= {1,1};
	for(int i=2; i<1500; i++) {
		if(!a[i]) {
			for(int j=i+i; j<1500; j+=i) {
				a[j]=1;
			}
		}
	}
	int T;
	scanf("%d",&T);
	while(T--) {
		int n,t,sum=0;
		scanf("%d",&n);
		for(int i=0; i<n; i++) {
			scanf("%d",&t);
			if(!a[t])
				sum+=t;
		}
		printf("%d\n",sum);
	}
	return 0;
}

The official solution honestly uses primality testing:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<stdio.h>
#include <math.h>
int main()
{
	int m,n,i,j,a[1000],flag=0;
	long s;
	scanf("%d",&m);
	while(m--)
	{
		s=0;
		scanf("%d",&n);
		for(i=0;i<n;i++)
		scanf("%d",&a[i]);
		for(i=0;i<n;i++)
		{
			if(a[i]==1)	continue;
			flag=0;
			for(j=2;j<=sqrt(a[i]);j++)
			{
				if(a[i]%j==0)
				{flag=1;break;}			
			}
			if(flag==0)	s+=a[i];
		}
	printf("%d\n",s);
	}
	return 0;
}        

Problem link: NYOJ 1022 Prime Summation Problem

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...