青岛市城市园林绿化局:编写一个函数输出300至500以内所有素数(即质数)中最大的前10个数之和k与300至500以内所有素数的个数

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/30 19:27:16

结果应该是4696 33
#include <algorithm>
#include <cmath>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;

void prime(int low,int high,int mid=10)
{
if (low>high || mid<0)
{
cerr<<"error"<<endl;
return;
}

vector< int > temp;
int num=0;

for(;low<=high;++low)
{
int i=2;
for(;low%i && i<=sqrt(low);++i);

if (low!=1 && i>sqrt(low))
{
++num;
temp.push_back(low);
}
}

if (mid>temp.size())
{
mid=temp.size();
}

partial_sort(temp.begin(),temp.begin()+mid,temp.end(),greater< int >());
int sum=accumulate(temp.begin(),temp.begin()+mid,0);

cout<<sum<<" "<<num<<endl;
}

int main()
{
prime(300,500);
return 0;
}

#include<stdio.h>
#include<math.h>

int main()
{
int i,j,temp,m=0,n=0,count=0;
float sum=0;
for(i=499;i>=301;i--)
{
temp=sqrt(i);
for(j=2;j<=temp;j++)
{
if(i/j==0)
{
m=1;
break;
}
}
if(m==0)
{
if(n<10)
{
sum=sum+i;
n++;
}
count++;
}
}
printf("top10 is:%5.2f\nThere are %d numbers\n" ,sum,count);
}
最后的结果是:4945 199