mercredi 5 août 2015

Finding Largest Twin Prime


I am trying to create a c program which prompts for user input and then, finds the largest twin prime within that number. This program then loops continuously, prompting the user for an input again and again and finding the largest twin prime until the user enters -1, after which it terminates. I wrote down the basic code, but have yet been able to make it loop continuously when using certain numbers such as 20 and 65. I cannot figure out what is wrong with my code.

I seem to be having another problem as well. For 20, the values show (15,17) instead of (17,19). Obviously the logic is wrong somewhere but I am not sure exactly where either.

This is my code:

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

int prime(int x)
{
    int i,numroot;
    numroot=sqrt(x);
    for(i=2;i<=numroot;i++)
    if(x%i==0){
        return(0);
    }
    return(1);

}

int main()
{
    double N;

    printf("This program prints out all the possible twin primes until a specific number which...\nyou can choose!");
    printf("\nA note of caution: Although this program accepts decimals, the value entered must be between 5 and 10^9,inclusive of the 2 numbers.");
    printf("\nKey in -1 to exit.");
    printf("\nEnter N value upto which twin primes ought to be calculated until: ");
    scanf("%lf",&N);

    while (N!=-1) {
      if (N<5 || N>pow(10,9)) {
          printf("\nNumber not in the valid range was inputted. \nPlease reenter the value: ");
          scanf("%lf",&N);
      }
      else {
          int n;
          n=floor(N);
              int prime(int x);
          int f,originalval;

          originalval=N;
          f=prime(n);
          while(f==0){//Calculates for largest prime number below user input
            n--;
            f=prime(n);
          }
          int smallint=n-2;
          while(prime(smallint)==1){
              n--;
              f=prime(n);
              while(f==0){
                  n--;
                  f=prime(n);
              }
              int smallint=n-2;
    }
    printf("The largest twin prime pair not above %d is (%d,%d)",originalval,smallint,n);
          printf("\nPlease re-enter the value:");
          scanf("%lf",&N);
      }
    }
    printf("\nProgram successfully terminated.");
    return 0;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire