All pastes #769721 Raw Edit

Miscellany

public c v1 · immutable
·published 2007-11-11 17:16 UTC
rendered paste body
#include <stdio.h>#include <stdlib.h>#define NUMBER_IS_PRIME -1#define TOO_MANY_FACTORS -2#define NO_INPUT -3#define _STEP_ 64#define MAX(a,b) (((a)>(b))?(a):(b))#define MIN(a,b) (((a)<(b))?(a):(b))char* getInput(){  int length = 0;  int input = 0;  char *text = malloc(_STEP_ + 1);  if (NULL == text)  {    return NULL;  }  while((input = getchar()) != EOF)  {    if ( (_STEP_ - 1) == (length % _STEP_) )    {      if (NULL == realloc(text, ( (length + 1) + _STEP_ + 1)))      {        free(text);        return NULL;      }    }    text[length] = input;    length++;  }  text[length] = '\0';  return text;}int mystrlen(char* string){  int lengthIndex = 0;  while (string[lengthIndex] != '\0')  {    lengthIndex++;  }  return lengthIndex;}int primefactors(int length){  int intToTest = length;  int nrOfFactors = 0, i = 0, factor_01 = 0;  //starts at i = 2, so 1 is not counted as a factor;  //if the while condition is TRUE, i is a factor of intToTest;  //everytime i is a factor, factors is being incremented;  //when factors reaches 3, the for-condition is FALSE, the loop stops  //and the last if-rule takes effect;  for (i = 2; (intToTest > 1) && (nrOfFactors < 3); i++)  {    while (i * (intToTest/i) == intToTest)    {      factor_01 = i;      intToTest /= i;      nrOfFactors++;    }  }  if (nrOfFactors == 1) //one factor found (prime itself) ==> prime  {    return NUMBER_IS_PRIME;  }  if (nrOfFactors == 2) //if there are exactly two factors  {    return factor_01;  }  if (nrOfFactors > 2) //if there are more than 2 factors  {    return TOO_MANY_FACTORS;  }  return 0;}void printArray(char* text, int factor_01, int factor_02){  int large = MAX(factor_01, factor_02);  int small = MIN(factor_01, factor_02);  int line = 0, row = 0;  for ( line = 1; line <= small; line++)  {    for ( row = line - 1 ; row < (large*small); row = row + small)    {      printf("%c", text[row]);    }    printf("\n");  }}int main(int args, char *argv[]){  char* text;  int length;  int factor;  text = getInput();  if (text==NULL)    return;  length = mystrlen(text)  if (length == 0)  {    printf("ERROR: No input\n");    free(text);    return NO_INPUT;  }  else if (length == 1) //if input is only one char  {    printf("%c\n", text[0]);    free(text);    return 0;  }  factor_01=primefactors(length);  if (factor == NUMBER_IS_PRIME)  {    printf("ERROR: Input length is prime\n");  }  if (factor == TOO_MANY_FACTORS)  {    printf("ERROR: Input length has too many prime factors\n");  }  if (factor > 0)  {    printArray(text, factor, length / factor_01);  }  free(text);  return 0;}