c语言编程题

求1到100的素数和,求代码
2024-11-18 02:40:15
推荐回答(4个)
回答(1):

#include
#include
int main()
{
unsigned int beg = 0, end = 0, tmp = 0, i = 0, j = 0;
unsigned long sum = 0;
printf("\nInput begin and end numbers:\n");
scanf("%d%d", &beg, &end);
if (beg > end)
{
tmp = beg;
beg = end;
end = tmp;
}
printf("\nCalculate sum of prime numbers between [%d, %d]:\n", beg, end);
for (i = beg; i <= end; ++i)
{
if (2 > i)
{
continue;
}
tmp = 1 + (int)sqrt((double)i);
for (j = 2; j <= tmp; ++j)
{
if (0 == i % j)
{
break;
}
}
if (j >= tmp || 2 == i)
{
sum += i;
printf("i = %d\t", i);
}
}
printf("\nsum = %d\n", sum);
return 0;
}
Input begin and end numbers:
1 100
Calculate prime number between [1, 100]:
i = 2 i = 3 i = 5 i = 7 i = 11 i = 13 i = 17 i = 19 i = 23 i = 29
i = 31 i = 37 i = 41 i = 43 i = 47 i = 53 i = 59 i = 61 i = 67 i = 71
i = 73 i = 79 i = 83 i = 89 i = 97
sum = 1060

回答(2):

#include
int IsPrime(int num)
{
int i=2;
for(;i<=num/2;i++)
if(0==num%i)
return 0;
return 1;
}
void main()
{
int sum=0;
int num;
for(num=2;num<=100;num++)
if(IsPrime(num))
sum+=num;
printf("%d ",sum);
}

------------物联网校企恋盟技术部

回答(3):

#include #include
int prime(int num);
int main (void){
int i, sum = 0;
for (i=2; i<=100; i++)
{
if (prime(i))
{
sum = sum + i;
}
}
printf ("%d\n", sum);
return 0;
}

int prime(int num) {
int k,time;
double stop;
time=0;
stop=sqrt(num);
for(k=2;k<=stop;k++)
{
if(num%k==0)
{
time++;
}
}

if(time==0 && num>1)
{
return 1;
}
else return 0;
}

回答(4):

#include
void main(){
int i,j,k=0,sum=0;
for(i=2;i<=10;i++){
k=0;
for(j=1;j<=i;j++){
if(i%j==0)
k++;
}
if(k==2)
sum+=i;
}
printf("%d\n",sum);
}