2015-02-12 44 views
-1

這個程序對我來說工作正常,但我一直在試圖找到一種方法來包含一個函數,它會找到我正在尋找的素數。我只是不明白如何將一個函數放入我的程序中。該程序會在給定的時間間隔內找到孿生素數以防萬一。轉換成函數

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

void main() 
{ 
    int low, high, n, count, i; 
    scanf ("%d %d", &low, &high); 
      count=0; 
      n=0; 
    if (low<=3) 
     count=count+1; 
    while (n<low) 
     n=n+6; 
    while (n<high) { 
     i=1; 
     int check; 
        check=0; 
     while (i*i<n+1) { 
      i=i+1; 
      if ((n-1)%i==0 || (n+1)%i==0) 
       check=1; 
     } 
     if (check!=1) 
      count=count+1; 
     n=n+6; 
    } 
    printf("There are %d twin primes between %d and %d\n", count, low, high); 
     printf(" \n"); 
} 
+1

它總是'int main' ... – Deduplicator 2015-02-12 00:57:49

+1

...它是一個函數.. – 2015-02-12 00:58:14

回答

0

這是你想要的嗎?

int findprime(int low, int high) { 
    int n, count, i; 

    count = 0; 
    n  = 0; 
    if (low <= 3) 
     count = count + 1; 
    while (n < low) 
     n = n + 6; 
    while (n < high) { 
     int check; 

     i  = 1; 
     check = 0; 
     while (i * i < n + 1) { 
      i = i + 1; 
      if ((n - 1) %i == 0 || (n + 1) % i == 0) 
       check = 1; 
     } 
     if (check != 1) 
      count = count + 1; 
     n = n + 6; 
    } 
    return count; 
} 

int main() { 
    int low, high, count; 
    count = 0; 
    if (scanf("%d %d", &low, &high) == 2) { 
     count = findprime(low, high); 
     printf("There are %d twin primes between %d and %d\n\n", count, low, high); 
    } else { 
     printf("Invalid input recieved.\n\n"); 
     return -1; 
    } 
    return 0; 
}