【经典100题】 题目12 判断101到200之间的素数

题目

判断 101-200 之间有多少个素数,并输出所有素数


C语言实现

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

_Bool isPrimeNumber(int t);//判断是不是素数
void main()
{
	int n = 0;
	for (int i = 101; i <= 201; i++)
	{
		if (isPrimeNumber(i))		
			printf("%d ", i);n++;		
	}
	printf("\n");
	printf("101到200之间的素数个数为:%d\n",n);
}

_Bool isPrimeNumber(int t)
{
	double result;
	if (t >= 1 & t <= 3)
		return 1;
	if (t > 3)
	{
		int n = 0;
		for (double i = 2; i <=t / 2; i++)
		{
			result = t / i;
			if (floor(result) == result) //判断能不能被整除
				n = n + 1;
		}
		if (n > 0)
			return 0;
		if (n == 0)
			return 1;
	}
}

运行结果:

101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
101到200之间的素数个数为:101
请按任意键继续. . .


python语言实现

import math
def isPrimeNumber(t):
    if t<=3 and t>= 0:
        return 1
    if t>3:
        n = 0
        for i in range(2,math.floor(t/2)+1):
            result = t/i
            if math.floor(result) == result:
               n = n+1
        if n>0:
           return 0

        else:            
           return 1

n = 0
for i in range(101,201):
  
    if isPrimeNumber(i):
       print(i,end = ' ')
       n = n+1
print()
print("101到200之间的素数个数为:%d"%n)

运行结果:

101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 
101到200之间的素数个数为:21


★finished by songpl, 2018.12.10

猜你喜欢

转载自blog.csdn.net/plSong_CSDN/article/details/84946033