Advertisement
Guest User

Untitled

a guest
Feb 24th, 2020
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3.  
  4. int main(void)
  5. {
  6.     long number = get_long("Type in your credit card number!\n");
  7.     long new_num = number;
  8.     int odd_num = 0;
  9.     int odd_sum = 0;
  10.     int even_sum = 0;
  11.     int card_length = 0;
  12.  
  13.     //copy number to use to get length
  14.     long new_num_copy = new_num;
  15.  
  16.     int length = 0;
  17.     while(new_num_copy > 0){
  18.         length++;
  19.         new_num_copy /= 10; // divide by 10 until you get to 0, the times you do that, is the length
  20.     } // variable length will be the lenth of new_num by the end of this
  21.  
  22.     int first_num = 0; //first number from the left
  23.     int second_num = 0; //second number from the left
  24.  
  25.     for (int i = length; i > 0; i--)
  26.     {  
  27.         //first condition for odd length numbers second for even length numbers
  28.         if((i == 1 && length % 2 != 0) || (i == 2 && length % 2 == 0)){
  29.             second_num = new_num  % 10; //if we hit the end, save second number
  30.         }
  31.  
  32.         even_sum += (new_num  % 10);
  33.         new_num /= 10;
  34.  
  35.         //first condition for odd length numbers second for even length numbers
  36.         if((i == 3 && length % 2 != 0) || (i == 2 && length % 2 == 0)){
  37.             first_num = new_num % 10; //if we hit the end, save first number too
  38.         }
  39.  
  40.         i--; // decrease again because we do new_num / 10 twice, shortening the numbers length, so just skip one step
  41.  
  42.         //odd_num calculation starts here
  43.         odd_num += ((new_num % 10) * 2);
  44.         new_num /= 10;
  45.         for (int j = 0; j < sizeof(odd_num); j++)
  46.         {
  47.             odd_sum += (odd_num % 10);
  48.             odd_num /= 10;
  49.         }
  50.     }
  51.  
  52.     if(length % 2 != 0){ //Switch them if length is odd, they are backwards when it's odd
  53.         int temp = first_num;
  54.         first_num = second_num;
  55.         second_num = temp;
  56.     }
  57.  
  58.     printf("\n%i -- %i\n",odd_sum,even_sum); //print the sums
  59.     printf("\n%i -- %i\n",first_num,second_num); //print the first and second number
  60.  
  61.     if ((odd_sum + even_sum) % 10 == 0) //final result and display error message if needed
  62.     {
  63.         return true;
  64.     } else {
  65.         printf("Card not valid!\n");
  66.         return false;
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement