#include #include #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=NULL; int length=0; int factor=0; int retVal=0; text = getInput(); if (text==NULL) return; length = mystrlen(text); switch (length) { case 0: printf("ERROR: No input\n"); retVal=NO_INPUT; break; case 1: printf("%c\n", text[0]); break; default: factor=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); break; } free(text); return 0; }