Advertisement
Guest User

Untitled

a guest
Nov 16th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.13 KB | None | 0 0
  1. #include "stdio.h"
  2. //9780000000000
  3. //9790000000000
  4.  
  5. int main(int argc, char
  6. const * argv[]) {
  7. //Constant
  8. const long DIVISOR = 10000000000; //10 zero's
  9. const int LOWER_BOUND = 100;
  10. const int UPPER_BOUND = 999;
  11. const int FIRST_VALID_PREFIX = 978;
  12. const int SECOND_VALID_PREFIX = 979;
  13. const int NUMBER_OF_DIGITS = 13;
  14. const long FORMULA_DIVISOR = 1000000000000; //13 zero's
  15. const int VALID = 0;
  16. const int INVALID_LESS_THAN_13 = 1;
  17. const int INVALID_MORE_THAN_13 = 2;
  18. const int INVALID_PREFIX = 3;
  19. const int INVALID_FORMULA = 4;
  20. // Read the number
  21. while (1) {
  22. int parseResult = 0;
  23. long isbn; //store input
  24. printf("Enter an ISBN: ");
  25. scanf("%ld", & isbn);
  26.  
  27. if (isbn < 0) {
  28. //Negative input - exit program
  29. printf("Program exits. Goodbye!!! \n");
  30. return 0;
  31. }
  32.  
  33. //Divide isbn by divisor constant
  34. int result = isbn / DIVISOR;
  35. if (result < LOWER_BOUND) {
  36. parseResult = INVALID_LESS_THAN_13;
  37. //printf("Invalid ISBN. Not enough 13 digits.");
  38. } else if (result > UPPER_BOUND) {
  39. parseResult = INVALID_MORE_THAN_13;
  40. //printf("Invalid ISBN. More than 13 digits.");
  41. }
  42.  
  43. if (result == FIRST_VALID_PREFIX || result == SECOND_VALID_PREFIX) {
  44. int result = 0; //store formula sum of digit
  45. long divisor = FORMULA_DIVISOR;
  46. for (int i = 0; i < NUMBER_OF_DIGITS; i++) {
  47. //get the digit at index of i
  48. int currentDigit = isbn / divisor;
  49. // printf("%i \n", currentDigit);
  50. if (i % 2 == 0) {
  51. //if i is even
  52. result += currentDigit;
  53. } else {
  54. //else i is odd
  55. result += 3 * currentDigit;
  56. }
  57. isbn = isbn - currentDigit * divisor;
  58. divisor = divisor / 10;
  59. // printf("current isbn is: %ld \n", isbn);
  60. }
  61. // printf("reulst is: %i", result);
  62. if (result % 10 != 0) {
  63. parseResult = INVALID_FORMULA;
  64. //printf("Invalid ISBN. Failed validation test.");
  65. }
  66. else {
  67. parseResult = VALID;
  68. }
  69. }
  70. //handle parse result
  71. if (parseResult == VALID) {
  72. printf("Valid ISBN. \n");
  73. } else if (parseResult == INVALID_LESS_THAN_13) {
  74. printf("Invalid ISBN. Not enough 13 digits. \n");
  75. } else if (parseResult == INVALID_MORE_THAN_13) {
  76. printf("Invalid ISBN. More than 13 digits. \n");
  77. } else if (parseResult == INVALID_PREFIX) {
  78. printf("Invalid ISBN. Wrong prefix element. \n");
  79. } else if (parseResult ==INVALID_FORMULA) {
  80. printf("Invalid ISBN. Failed validation test. \n");
  81. }
  82. }
  83. return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement