Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdio.h"
- //9780000000000
- //9790000000000
- int main(int argc, char
- const * argv[]) {
- //Constant
- const long DIVISOR = 10000000000; //10 zero's
- const int LOWER_BOUND = 100;
- const int UPPER_BOUND = 999;
- const int FIRST_VALID_PREFIX = 978;
- const int SECOND_VALID_PREFIX = 979;
- const int NUMBER_OF_DIGITS = 13;
- const long FORMULA_DIVISOR = 1000000000000; //13 zero's
- const int VALID = 0;
- const int INVALID_LESS_THAN_13 = 1;
- const int INVALID_MORE_THAN_13 = 2;
- const int INVALID_PREFIX = 3;
- const int INVALID_FORMULA = 4;
- // Read the number
- while (1) {
- int parseResult = 0;
- long isbn; //store input
- printf("Enter an ISBN: ");
- scanf("%ld", & isbn);
- if (isbn < 0) {
- //Negative input - exit program
- printf("Program exits. Goodbye!!! \n");
- return 0;
- }
- //Divide isbn by divisor constant
- int result = isbn / DIVISOR;
- if (result < LOWER_BOUND) {
- parseResult = INVALID_LESS_THAN_13;
- //printf("Invalid ISBN. Not enough 13 digits.");
- } else if (result > UPPER_BOUND) {
- parseResult = INVALID_MORE_THAN_13;
- //printf("Invalid ISBN. More than 13 digits.");
- }
- if (result == FIRST_VALID_PREFIX || result == SECOND_VALID_PREFIX) {
- int result = 0; //store formula sum of digit
- long divisor = FORMULA_DIVISOR;
- for (int i = 0; i < NUMBER_OF_DIGITS; i++) {
- //get the digit at index of i
- int currentDigit = isbn / divisor;
- // printf("%i \n", currentDigit);
- if (i % 2 == 0) {
- //if i is even
- result += currentDigit;
- } else {
- //else i is odd
- result += 3 * currentDigit;
- }
- isbn = isbn - currentDigit * divisor;
- divisor = divisor / 10;
- // printf("current isbn is: %ld \n", isbn);
- }
- // printf("reulst is: %i", result);
- if (result % 10 != 0) {
- parseResult = INVALID_FORMULA;
- //printf("Invalid ISBN. Failed validation test.");
- }
- else {
- parseResult = VALID;
- }
- }
- //handle parse result
- if (parseResult == VALID) {
- printf("Valid ISBN. \n");
- } else if (parseResult == INVALID_LESS_THAN_13) {
- printf("Invalid ISBN. Not enough 13 digits. \n");
- } else if (parseResult == INVALID_MORE_THAN_13) {
- printf("Invalid ISBN. More than 13 digits. \n");
- } else if (parseResult == INVALID_PREFIX) {
- printf("Invalid ISBN. Wrong prefix element. \n");
- } else if (parseResult ==INVALID_FORMULA) {
- printf("Invalid ISBN. Failed validation test. \n");
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement