C language: input the integer m, and store all prime numbers greater than 1 and less than the integer m into the specified array

After a winter vacation, when I looked at this question again, I forgot to determine the prime number...

  1. Code display
  2. Code analysis

Code display:

#include <stdio.h>

int main(void)
{
    
    
	int m, cnt = 0, i, j;
	int array[101];
	printf("Input:\nPlease input a number: \n");
	scanf("%d", &m);
	for (i = 2; i < m; i++)//该循环体判定范围内的所有数字是否为素数
	{
    
    
		for (j = 2; j < i; j++)//该数是否为素数
		{
    
    
			if (i % j == 0)//从2开始到该数字,这个范围内,该数字能被整除,则不为素数
			{
    
    
				break;
			}
		}
		if (j == i)//都未被整除,则该数为素数,将其赋值给数组
		{
    
    
			array[cnt++] = i;//同时计算个数,是否越界。
		}
		if (cnt > 100)//越界,跳出循环
		{
    
    
			break;
		}
	}

	printf("Output:\n");//以下情况判定
	if (m <= 0)
	{
    
    
		printf("error!\n");
	}
	else if (cnt > 100)
	{
    
    
		printf("overflow!\n");
	}
	else
	{
    
    
		printf("n=%d\n", cnt);
		for (i = 0; i < cnt; i++)
		{
    
    
			printf("%5d", array[i]);//输出以及换行。
			if ((i + 1) % 15 == 0)
			{
    
    
				printf("\n");
			}
		}
		printf("\n");

	}
	return 0;
}

Code analysis:

Part of the analysis is in the code. The
overall code writing process is divided into prime number judgment and assignment, and loop matching conditions.
Then follow the regulations and cooperate with the conditional statement for output.

Very simple, but not complete.

Guess you like

Origin blog.csdn.net/yooppa/article/details/114749938
Recommended