[英]C programming - finding prime numbers
一位朋友給我此代碼以查找1-40的質數
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
//print prime numbers from 1-40
int i, j;
int factor = 0; //this will be 1 if a factor is found
//otherwise 0
//so factor = 1 means not a prime number
printf("Prime numbers from 1 to 40 are: ");
for (i = 1; i < 41; i++)
{
for (j = 2; j <= (i / 2); j++)
{
if (factor == 0)
{
if (i % j == 0)
factor = 1;
else
factor = 0;
}
}
if (factor != 1)
{
printf("%d ", i);
}
factor = 0;
}
getch();
}
我沒有得到循環的第二部分。為什么j從2開始,為什么它小於(i / 2)而不是i?
謝謝。
為什么j以2開頭
因為1是所有數字(包括質數)的因數,所以您無需為此進行測試。 (外循環可能也應該從2開始,因為按照慣例,通常不將1視為質數。)
為什么它小於
(i / 2)
而不是i
?
無需檢查大於i
平方根的因數,因為如果存在這樣的因數f
,那么i/f
因子也將小於平方根。
但是平方根很難計算,因此該版本使用i/2
作為更簡單但更寬松的上限。 只要i
至少為4,它至少與平方根一樣大。
它以2開頭,因為2是最小的質數(1不被視為質數),以i / 2結束,因為數n的最大因數最多為n/2
。
如果從1開始,您將找不到任何質數,因為每個數字都可以被1整除。
至於第二部分,我將使用矛盾證明。 假設n可被大於n/2
的數m
整除。 那么n也可以被n/m
整除,但是m>n/2 implies
2 * m> n which means that n must be divisible by an integer less than 2, but the only such integer is 1, which would imply that
m = 1 `。 因此,n在n / 2和n之間可以沒有除數。
why does j start with 2
What is prime number?
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
注意other than one
的關鍵字。
and why is it less than (i / 2) and not i?
素數有一個規則“如果不能在sqrt之下將其除以兩倍,則它是素數”。 因此,請檢查最多兩倍的sqrt。
在這里查看更多優化
您需要開始查找給定的數字是否可以被2、3,...整除,直到找到的數字的一半。 如果一個數字可被小於或小於該數字的整數整除而不留下余數,則該數字不是質數。 一旦達到數字值的一半,就需要檢查其余數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.