Advertisement
snakerdlk

Desafio Geek - solução

Aug 25th, 2011
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define BUFFER_SIZE 1024
  6.  
  7. int checkPrime(char *);
  8.  
  9. int main(int argc, char **argv){
  10.     if(argc != 2){
  11.         printf("Usage: %s <size of palindrome>\n", argv[0]);
  12.         exit(0);
  13.     }
  14.  
  15.     unsigned size = atoi(argv[1]);
  16.     if(size < 2){
  17.         printf("Size of palindrome must be greater than 1\n");
  18.         exit(0);
  19.     }
  20.  
  21.     char buffer[BUFFER_SIZE];
  22.     char read[BUFFER_SIZE];
  23.     char *aux = (char *) malloc(sizeof(char) * size);
  24.     unsigned index;
  25.     unsigned length;
  26.     unsigned counter;
  27.     unsigned first, last;
  28.  
  29.     while(fgets(read, BUFFER_SIZE-size, stdin) != NULL){
  30.         snprintf(buffer, BUFFER_SIZE, "%s%s", &buffer[strlen(buffer)-size+1], read);
  31.  
  32.         index = 0;
  33.         length = strlen(buffer)-size;
  34.         while(index < length){
  35.             for(counter = 0; counter < size/2; counter++){
  36.                 first = index+counter;
  37.                 last = index+ (size-1) -counter;
  38.                 if(buffer[first] != buffer[last]){
  39.                     break;
  40.                 }
  41.             }  
  42.             if(counter == size/2){
  43.                 for(counter = 0; counter < size; counter++){
  44.                     aux[counter] = buffer[index+counter];
  45.                 }
  46.                 aux[counter] = '\0';
  47.                 printf("%s - palindrome!", aux);
  48.  
  49.                 if(checkPrime(aux) == 0){
  50.                     printf(" IS PRIME!");
  51.                 }else{
  52.                     printf(" ...");
  53.                 }
  54.                 printf("\n");
  55.             }
  56.             index++;
  57.         }
  58.     }      
  59.     free(aux);
  60.     return 0;
  61.  
  62. }
  63.  
  64. int checkPrime(char *number){
  65.     unsigned long long num = atol(number);
  66.     unsigned long long max = num/2;
  67.     unsigned long long counter = 0;
  68.  
  69.     if(num % 2 == 0){
  70.         return 2;
  71.     }
  72.     for (counter = 3; counter < max;counter+=2){
  73.         if(num % counter == 0){
  74.             return counter;
  75.         }
  76.     }
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement