簡體   English   中英

C-查找素數

[英]C - Find Prime number

這是我的質數函數,我有問題。
為什么我通過2147483647時它返回0

int     ft_is_prime(int nb)
{
  if (nb<2)
    return (0);
  else if (nb==2)
    return (1);
  else if (nb%2==0)
    return (0);
  else 
  {
    int i=3;
    int carre=9;
    while (carre <= nb)
    {
        if (nb % i == 0)
            return (0);
        carre=carre+4*i+4;
        i=i+2;
    }
    return (1);
  }
}

正如@ Eugene-Sh所說,計算carre會發生溢出。

另外,標准int至少為16位。 但是現在大多數編譯器都將其設置為32位。 因此,至少您應該檢查該限制,以使您的代碼在所有方面都能正常運行。

更改為long long以確保您在carrenb都能獲得良好的結果,從而獲得64位。 但這只是道路的一半。 如評論中所述,當超過此限制時,您仍然可能會溢出。

所以像這樣,不改變類型:

int max = INT_MAX; // from limits.h
int maxsqrt = sqrt(INT_MAX); // cast to int, such that maxsqrt² is the max square
if (maxsqrt % 2 == 0)
   maxsqrt--; // only odd number considered
int maxcarre = maxsqrt*maxsqrt; // this is the max square (carre in french) for an odd INT

然后在你的循環,你現在可以檢查是否carre是最后一個,你可以計算出,因為maxcarre是最大的一個:

while (carre <= nb)
{
    if (nb % i == 0)
        return (0);
    if (carre >= maxcarre) // this is the last odd square we could compute before overflow
        return (-1); // if this -1 represents a "don't" know code for you
    carre=carre+4*i+4; // this compute the next square of an odd number 
    i=i+2;
}

但是我建議至少使用long (因此將max更改為LONG_MAX )以便獲得更多的容量,並且仍在CPU的范圍內(現代編譯器為64位),或者甚至long long因為至少它是64位在所有編譯器上。

正如@Veltas所說:long在某些64位編譯器實現中為64位。 它不依賴於操作系統。 此外,IIRC Microsoft的VC ++在64位上也使用32位長。

感謝@ Veltas,@ EugeneSh。 和其他幫助人們的寶貴反饋!

#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
/* As we know 2,3,5,7,11..19....
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.
so the formula in if we have n numbers as a input
how we find the prime number ,the formula is
divisible by 2 ...n-1. so 3%2=1 then 3 is a
prime number,10%2=0 so 10 is not a prime number 
now 9%2=1 but 9%3=0 that is why we will make a 
condition of for loop that divisible 9 with all
the numbers from 2...9-1 and find out whether it 
divisible value is 0.    
*/
int main()
{
    int i,n,j;
 bool flag;
    printf("Enter the Range Number:");
    scanf("%d",&n);
        for(i=2;i<=n;i++)
        { bool flag=true;
            for(j=2;j<=i-1;j++) 
            {

                if (i%j==0){
            flag=false;
            break;}
            }
 if (flag==true)
                printf("%d\n",i);
            }

    return 0;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM