Update: I already figured out what's wrong, it's the function of adding the digits together. Some also pointed out how some parts of this code is unnecessary so I deleted it and it definitely helped! I was able to point out the problem more easily. Thank you guyss, appreciate it I'm trying to figure out what I did wrong in the first step of the credit problem in CS50. Im trying to create a program that implements the Luhn algorithm. I already figured out how to add every other digit starting from the least significant one. But I have a problem in the part of multiplying every other digit by 2, and adding the digits of the products together individually. I first decided to do an array but I tried to do now a while loop since someone suggested it can be solved thru a loop. When I type in the credit number 4003600000000014, it returns the value of 24 instead of 13. I cant figure out the logical error, and ive already tried to solve it for hours. Would definitely appreciate your help!
#include <stdio.h>
#include <cs50.h>
int sum_digits(int number2);
int get_number_digits(long x);
int times_two(int x);
int main(void) {
//Prompt for input
long number = get_long("Card Number: \n");
//initialize number to two different variables for [1. multiplying by
//2, adding the products]
//[2. adding every other digit]
long number2 = number;
long number3 = number;
//Calculate checksum
//Multiply digits by 2 alternately starting from the tens place, then
//add the digit of the products NOTE: edit loop, something is wrong
long remainderr2, currentnumber2, product, initialsum;
currentnumber2 = number3 / 10;
number3 = currentnumber2;
int finalsum = 0;
while (currentnumber2 > 0)
{
number3 = currentnumber2;
remainderr2 = currentnumber2 % 10;
product = times_two(remainderr2);
initialsum = sum_digits(product);
finalsum = finalsum + initialsum;
currentnumber2 = currentnumber2 / 10;
currentnumber2 = currentnumber2 / 10;
}
printf("%ld", finalfinalsum);
}
//Function that adds the digits of a number
int sum_digits(int number2) {
int secondstep, remainderr, currentnumber, sum;
currentnumber = number2;
secondstep = 0;
while (number2 > 0) {
number2 = currentnumber;
sum = 0 + secondstep;
remainderr = currentnumber % 10;
secondstep = sum + remainderr;
currentnumber = number2 / 10;
}
return sum;
}
//Function that multiplies int by 2
int times_two(int x) {
x = x * 2;
return x;
}