南陽OJ-No.22
時間限制3000ms,內存限制65535KB
描述
現在給你N個數(0 < N < 1000),現在要求你寫出一個程序,找出這N個數中的所有素數,並求和。
輸入
第一行給出整數M(0 < M < 10)代表多少組測試數據
每組測試數據第一行給你N,代表該組測試數據的數量。
接下來的N個數爲要測試的數據,每個數小於1000
輸出
每組測試數據結果佔一行,輸出給出的測試數據的所有素數和
樣例輸入
3
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
樣例輸出
10
41
52
java
時間135,內存1515
import java.util.Scanner;
public class Main {
public static Scanner cin = new Scanner(System.in);
public static void main(String[] args) throws Exception{
int line = cin.nextInt();
int sum;
int[] s;
while(line>=1) {
s = getInt();
sum = 0;
for (int i=0; i<s.length; i++) {
if(isPrime(s[i])) {
sum += s[i];
}
}
System.out.println(sum);
line --;
}
}
public static int[] getInt() {
int x = cin.nextInt();
int[] s = new int[x];
for(int i=0; i<s.length; i++) {
s[i] = cin.nextInt();
}
return s;
}
public static boolean isPrime(int x) {
if (x == 1) {
return false;
}
for (int i=2; i<x; i++) {
if(x%i == 0) {
return false;
}
}
return true;
}
}
時間140,內存1523
import java.util.Scanner;
public class Main {
public static Scanner cin = new Scanner(System.in);
public static void main(String[] args) throws Exception{
int line=cin.nextInt();
int sum;
int[] s;
while(line>=1){
s = getInt();
sum = 0;
for (int i=0; i<s.length; i++)
if(isPrime(s[i]))
sum += s[i];
System.out.println(sum);
line --;
}
}
public static int[] getInt(){
int x = cin.nextInt();
int[] s = new int[x];
for(int i=0; i<s.length; i++)
s[i] = cin.nextInt();
return s;
}
public static boolean isPrime(int x){
if (x == 1)
return false;
for (int i=2; i<x; i++)
if(x%i == 0)
return false;
return true;
}
}
僅僅把括號省略,以爲更簡潔,反而系統不情願???注意書寫規範
時間50,內存61
僅供參考
import java.io.IOException;
public class Main {
public static int getInt() throws IOException{
int i;
while((i = System.in.read()) < 48 || i > 57);
int temp = 0;
while(i > 47 && i < 58){
temp = temp * 10 + i - 48;
i = System.in.read();
}
return temp;
}
public static boolean isPrime(int n){
if(n < 2)
return false;
int len = (int)Math.sqrt(n) + 1;
for(int i = 2;i < len; i++)
if(n%i == 0)
return false;
return true;
}
public static void main(String args[]) throws IOException{
int i, j, t, sum;
for (i = getInt(); i > 0; i--) {
sum = 0;
for(j = getInt(); j > 0; j--)
if (isPrime(t = getInt()))
sum += t;
System.out.println(sum);
}
}
}
C++
時間12,內存240
#include<iostream>
using namespace std;
bool isPrime(int x)
{
if(x==1)
return false;
for(int i=2; i<x; i++)
if(x%i==0)
return false;
return true;
}
int main()
{
int line, base, sum;
cin >> line;
while(line--)
{
sum = 0;
cin >> base;
int s[base];
for(int i=0; i<base; i++)
cin >> s[i];
for(int i=0; i<base; i++)
if(isPrime(s[i]))
sum += s[i];
cout << sum << endl;
}
return 0;
}
時間4,內存240
#include<stdio.h>
int prime(int n)
{
int a=2;
while(n>=a)
if(!(n%a++))
break;
if(a==n+1&&n!=1)
return 1;
return 0;
}
int main()
{
int n,m;
int a[1024];
scanf("%d",&n);
while(n--)
{
int sum=0;
scanf("%d",&m);
for(int i = 0;i<m;++i)
scanf("%d",&a[i]);
for(int i = 0;i<m;++i)
if(prime(a[i]))
sum+=a[i];
printf("%d\n",sum);
}
return 0;
}