Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <stdio.h>
- int main(void)
- {
- long number = get_long("Type in your credit card number!\n");
- long new_num = number;
- int odd_num = 0;
- int odd_sum = 0;
- int even_sum = 0;
- int card_length = 0;
- //copy number to use to get length
- long new_num_copy = new_num;
- int length = 0;
- while(new_num_copy > 0){
- length++;
- new_num_copy /= 10; // divide by 10 until you get to 0, the times you do that, is the length
- } // variable length will be the lenth of new_num by the end of this
- int first_num = 0; //first number from the left
- int second_num = 0; //second number from the left
- for (int i = length; i > 0; i--)
- {
- //first condition for odd length numbers second for even length numbers
- if((i == 1 && length % 2 != 0) || (i == 2 && length % 2 == 0)){
- second_num = new_num % 10; //if we hit the end, save second number
- }
- even_sum += (new_num % 10);
- new_num /= 10;
- //first condition for odd length numbers second for even length numbers
- if((i == 3 && length % 2 != 0) || (i == 2 && length % 2 == 0)){
- first_num = new_num % 10; //if we hit the end, save first number too
- }
- i--; // decrease again because we do new_num / 10 twice, shortening the numbers length, so just skip one step
- //odd_num calculation starts here
- odd_num += ((new_num % 10) * 2);
- new_num /= 10;
- for (int j = 0; j < sizeof(odd_num); j++)
- {
- odd_sum += (odd_num % 10);
- odd_num /= 10;
- }
- }
- if(length % 2 != 0){ //Switch them if length is odd, they are backwards when it's odd
- int temp = first_num;
- first_num = second_num;
- second_num = temp;
- }
- printf("\n%i -- %i\n",odd_sum,even_sum); //print the sums
- printf("\n%i -- %i\n",first_num,second_num); //print the first and second number
- if ((odd_sum + even_sum) % 10 == 0) //final result and display error message if needed
- {
- return true;
- } else {
- printf("Card not valid!\n");
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement