cs50 Credit issue with identifying card company - cs50

I'm completely new to programming and have been working through pset1 this week but credit is proving to be a bit tough. I've managed to get the checksum working but I'm having real trouble identifying which company the card belongs to, the last part of the code seems to introduce more errors every time I try to fix it. I would really appreciate it if anybody could point me in the right direction.
#include <cs50.h>
#include <stdio.h>
int main (void)
{
long long ccnumber;
do
{
ccnumber = get_long_long("Credit card number: ");
}
while (ccnumber < 0);
long long cc = ccnumber;
int s1;
while (cc > 0)
{
int l1 = cc % 10;
s1 = s1 + l1;
cc = cc / 100;
}
cc = ccnumber / 10;
int s2;
while (cc > 0)
{
int l1 = cc % 10;
l1 = l1 * 2;
if (l1 > 9) l1 = l1 % 10 + l1 / 10;
s2 = s2 + l1;
cc = cc / 100;
}
int s3 = s1 + s2;
if (s3 % 10 == 0)
s3 = true;
long long n = ccnumber;
int count = 0;
while (n != 0)
{
n /= 10;
++count;
}
int twonumbers = ccnumber;
while(twonumbers >= 100)
{
twonumbers = twonumbers / 10;
}
int firstnumber = ccnumber;
while(firstnumber >= 10)
{
firstnumber = firstnumber / 10;
}
if (twonumbers == 34 || 37 && (count == 15 ))
printf("AMERICAN EXPRESS\n");
else if (twonumbers == 51 || 52 || 53 || 54 | 55 && (count == 16 ))
printf("MASTER CARD\n");
else if (firstnumber == 4 && (count == 13 || 16 ))
printf("VISA\n");
else
printf("INVALID\n");
}

Your ending if statements are not correct:
if (twonumbers == 34 || 37 && (count == 15 ))
...
should be
if ((twonumbers == 34 || twonumbers == 37) && (count == 15 ))
And the same for each if statement - you have to repeat what is being compared for every or statement or the compiler will assume "true" as in this case, 37 is no equal to 0.
Not, you can also compare ranges as well:
else if (twonumbers >= 51 && twonumbers <= 55 && count == 16)
Note I also correct a binary or there on the last compare (you had only 1 | and not 2 ||)
The last is
else if (firstnumber == 4 && (count == 13 || count == 16 ))
I also question what:
int s3 = s1 + s2;
if (s3 % 10 == 0)
s3 = true;
is doing as this will actually always be "true" in a C sense, but in reality, you don't actually use s3 anywhere so I am confused.
Lastly, turn on all compiler warning. It would have told you about a lot of the things I mention here.
Now, I am not saying that this is the only thing wrong here, but it was the most obvious.

Related

CS50 Credit: Always getting INVALID return

Was attempting Credit from CS50 and kept getting INVALID return from my code. I approached this problem by using arrays even though it may not have been the best method. Code compiles with no issues.
My pseudocode logic was:
1) obtain card number
2) use loop to find number of digits
3) check if card contains 13, 15 or 16 digits
4) if so, write digits from long into array
5) have a copy of original array to multiply every other number by 2
6) add the digits of the product
7) check for card length and starting digits
Here is my code:
#include <stdio.h>
#include <cs50.h>
int main(void)
{
// Get credit card number
long num = get_long("Number: ");
// Find number of digits
int digits = 0;
while (num > 0)
{
num /= 10;
digits++;
}
// Check if number of digits is within possible range
if (digits != 13 && digits != 15 && digits != 16)
{
printf("INVALID\n");
}
int originalnumber[digits];
// Write each digit of credit card number into an array
for (int i = digits - 1; i >= 0; i--)
{
originalnumber[i] = num % 10;
num = num / 10;
}
// Multiply alternate digits by 2
int number[digits];
for (int i = 0; i < digits; i++)
{
number[i] = originalnumber[i];
}
for (int i = 1; i < digits; i+=2)
{
number[i] = number[i] * 2;
}
// Add product digits
int sum = 0;
int temp;
for (int i = 0; i < digits; i++)
{
temp = (number[i] % 10) + ((number[i] / 10) % 10);
sum = sum + temp;
}
// Check for card length and starting digits
// AMEX
if (digits == 15)
{
if (originalnumber[14] == 3 && sum % 10 == 0 && (originalnumber[13] == 4 || originalnumber[13] == 7))
{
printf("AMEX\n");
return 0;
}
}
// MasterCard
if (digits == 16)
{
if (originalnumber[15] == 5 && sum % 10 == 0 && (originalnumber[14] == 1 || originalnumber[14] == 2 || originalnumber[14] == 3 || originalnumber[14] == 4 || originalnumber[14] == 5))
{
printf("MASTERCARD\n");
return 0;
}
}
// Visa
if (digits == 13)
{
if (originalnumber[12] == 4 && sum % 10 == 0)
{
printf("VISA\n");
return 0;
}
}
if (digits == 16)
{
if (originalnumber[15] == 4 && sum % 10 == 0)
{
printf("VISA\n");
return 0;
}
}
printf("INVALID\n");
return 1;
}
I tried debug50 and it seems that when I try to sum the digits together using temp and sum, the loop completes with sum still being 0. May I know what is wrong here? Is the flow of my pseudocode wrong or are there any glaring mistakes that I may have overlooked? (stared at this for way too long..)
Thank you in advance!
If sum is always 0, regardless of whether that is what you expect, sum % 10 would always be 0, so that is not the "false" that is failing the tests.
Which should direct your attention to originalnumber.
What is the value of num after this loop?
while (num > 0)
{
num /= 10;
digits++;
}

responce to multi numbers

im trying to make a specific responce for a set of numbers but i dont know the exact code for that for exemple i want the responce for only numbers in between 10 and 15 it doesnt interupt with the other 2 results
module.exports.run = async (bot, message, args) => {
var s, final;
var random = Math.floor(Math.random() *( 10000)) /500;
s = random + .005 + '',
final = s.substring(0, s.indexOf('.') + 3);
message.reply("Your BC Mark is " + final);
if (final + 16 > 16){
message.reply(`excellent mark !`)
}
if (final + 10 > 15 ){
message.reply(`good !`)
}
if (final + 1 < 10.5) {
message.reply(`not bad !`)
}
}
module.exports.help = {
name: "bac"
}
You could check if your number is greater than or equal to a value and also less than or equal to a value. This would create your intended ranges.
Test the code below and implement it as necessary.
const num = 8;
if (num >= 1 && num <= 5) console.log('Between 1 and 5.');
if (num >= 6 && num <= 10) console.log('Between 6 and 10.');
if (num >= 11 && num <= 15) console.log('Between 11 and 15.');
More about comparison operators.

CS50 pset 1 - Credit, more comfortable

I have the following errors
:( identifies 5105105105105100 as MASTERCARD
expected "MASTERCARD\n", not "INVALID\n"
:( identifies 4111111111111111 as VISA
expected "VISA\n", not "INVALID\n"
:( identifies 4012888888881881 as VISA
expected "VISA\n", not "INVALID\n"
but for the card to be correct the last digit should be which is correct in my case. Please help
------------------- CODE -----------------------
#include <cs50.h>
#include <stdio.h>
int main()
{
long long cardNumber;
// get a card number from the user
do
{
printf("Your card number please: ");
//scanf("%lld", &cardNumber);
cardNumber = get_long_long();
}
while (cardNumber < 0);
//check the length of the card
int counter = 0;
long long cardNumberNeo = cardNumber;
while (cardNumberNeo > 0)
{
cardNumberNeo = cardNumberNeo / 10;
counter++;
}
if (counter != 15 && counter != 16 && counter != 13)
{
printf("INVALID\n");
}
// Array of card number
cardNumberNeo = cardNumber;
int cardNumberArr[counter], cardNumberArrNeo[counter], i;
for (i=0; i<counter; i++)
{
cardNumberArr[counter-i-1] = cardNumberNeo % 10;
cardNumberArrNeo[counter-i-1] = cardNumberArr[counter-i-1];
cardNumberNeo = cardNumberNeo / 10;
}
for (int i = 1; i < counter; i+=2)
{
cardNumberArrNeo[i] = cardNumberArrNeo[i] * 2;
}
int oddNumber = 0;
int temp;
for (int i = 0; i < counter; i++)
{
temp = (cardNumberArrNeo[i] % 10) + (cardNumberArrNeo[i]/10 % 10);
oddNumber = oddNumber + temp;
}
if (oddNumber % 10 == 0)
{
// Check the type of the card
if ( ((cardNumberArr[0] == 3 && cardNumberArr[1] == 4) || (cardNumberArr[0] == 3 && cardNumberArr[1] == 7)) && counter == 15 )
{
printf("AMEX\n");
}
else if (cardNumberArr[0] == 5 && cardNumberArr[1] >= 1 && cardNumberArr[1] <= 5 && counter == 16)
{
printf("MASTERCARD\n");
}
else if (cardNumberArr[0] == 4 && (counter == 13 || counter == 16 ))
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
else
{
printf("INVALID\n");
}
return 0;
}
This will work.....as long as the credit card number has an odd length. Remember, Luhn's algorithm rule [emphasis added]:
Multiply every other digit by 2, starting with the number’s
second-to-last digit, and then add those products' digits together.
This loop for (int i = 1; i < counter; i+=2) processes the wrong digits for a card with even length. Such numbers need to start at the 0th index in order to end up at the correct place (ie penultimate digit).

How should I fix my infinite while loop that takes in 3 conditions? Also stylistic questions for novice

writing code to test the Hailstone Sequence, also called Collatz conjecture. Code will print out the number of iterations of the Hailstone sequence.
def main():
start_num = eval (input ("Enter starting number of the range: "))
end_num = eval (input ("Enter ending number of the range: "))
The main problem is that my code returns an infinite loop. I want to check all of these conditions in one statement
while (start_num > 0 and end_num > 0 and end_num > start_num):
cycle_length = 0
max_length = 0
max_number = 0
my code seems inefficient, there is probably a better way to approach the problem
for i in range(start_num, (end_num + 1)):
cycle_length = 0
while (i != 1):
if (i % 2 == 0):
i = i // 2
cycle_length += 1
if (i % 2 == 1):
i = ((3 * i) + 1)
cycle_length += 1
print (cycle_length)
I just started coding, and I always know that there is a more efficient way to approach these problems. Any suggestions on methodology, problem solving, or stylistic advice would be greatly appreciated.
Here is an answer in java. I assume that we will not start with 1.
public static void main(String[] args) {
int counter =0;
Scanner sc = new Scanner(System.in);
System.out.println("Give us a number to start with:");
int start = sc.nextInt();
System.out.println("Give us a number to end with:");
int end = sc.nextInt();
if (end > start) {
for (int i = 0; i <= end - start; i++) {
counter = 0;
int num = start + i;
int temp = num;
while(temp != 1) {
if ( temp % 2 == 0 ) {
temp = temp / 2;
} else {
temp = 3* temp +1;
}
counter++;
}
System.out.println(num + " takes " + counter + "iterations.");
}
} else {
System.out.println("Your numbers do not make sense.");
}
}
Here's an answer in python in case you're staying up late trying to solve this problem. :P Have a good night.
start_num = 1
end_num = 10
for i in range(start_num, (end_num + 1)):
cycle_length=0
num = i
while (num != 1):
if (num % 2 == 0):
num = num // 2
cycle_length+=1
else:
num = ((3 * num) + 1)
cycle_length+=1
print(cycle_length)

KMP prefix table

I am reading about KMP for string matching.
It needs a preprocessing of the pattern by building a prefix table.
For example for the string ababaca the prefix table is: P = [0, 0, 1, 2, 3, 0, 1]
But I am not clear on what does the numbers show. I read that it helps to find matches of the pattern when it shifts but I can not connect this info with the numbers in the table.
Every number belongs to corresponding prefix ("a", "ab", "aba", ...) and for each prefix it represents length of longest suffix of this string that matches prefix. We do not count whole string as suffix or prefix here, it is called self-suffix and self-prefix (at least in Russian, not sure about English terms).
So we have string "ababaca". Let's look at it. KMP computes Prefix Function for every non-empty prefix. Let's define s[i] as the string, p[i] as the Prefix function. prefix and suffix may overlap.
+---+----------+-------+------------------------+
| i | s[0:i] | p[i] | Matching Prefix/Suffix |
+---+----------+-------+------------------------+
| 0 | a | 0 | |
| 1 | ab | 0 | |
| 2 | aba | 1 | a |
| 3 | abab | 2 | ab |
| 4 | ababa | 3 | aba |
| 5 | ababac | 0 | |
| 6 | ababaca | 1 | a |
| | | | |
+---+----------+-------+------------------------+
Simple C++ code that computes Prefix function of string S:
vector<int> prefixFunction(string s) {
vector<int> p(s.size());
int j = 0;
for (int i = 1; i < (int)s.size(); i++) {
while (j > 0 && s[j] != s[i])
j = p[j-1];
if (s[j] == s[i])
j++;
p[i] = j;
}
return p;
}
This code may not be the shortest, but easy to understand flow of code.
Simple Java Code for calculating prefix-Array-
String pattern = "ababaca";
int i = 1, j = 0;
int[] prefixArray = new int[pattern.length];
while (i < pattern.length) {
while (pattern.charAt(i) != pattern.charAt(j) && j > 0) {
j = prefixArray[j - 1];
}
if (pattern.charAt(i) == pattern.charAt(j)) {
prefixArray[i] = j + 1;
i++;
j++;
} else {
prefixArray[i] = j;
i++;
}
}
for (int k = 0; k < prefixArray.length; ++k) {
System.out.println(prefixArray[k]);
}
It produces the required output-
0
0
1
2
3
0
1
Python Implementation
p='ababaca'
l1 = len(p)
j = 0
i = 1
prefix = [0]
while len(prefix) < l1:
if p[j] == p[i]:
prefix.append(j+1)
i += 1
j += 1
else:
if j == 0:
prefix.append(0)
i += 1
if j != 0:
j = prefix[j-1]
print prefix
I have tried my hands using the Javascript, Open for suggestions.
const prefixArray = function (p) {
let aux = Array(p.length).fill(0);
// For index 0 the matched index will always be 0, so we will we start from 1
let i = 1;
let m = 0; // mismatched index will be from 0th
// run the loop on pattern length
while ( i < p.length) {
// 3 Cases here
// First when we have a match of prefix and suffix of pattern
if(p.charAt(i) === p.charAt(m)) {
// increment m
m++;
// update aux index
aux[i] = m;
// update the index.
i++;
}
// Now if there is no match and m !=0 means some match happened previously
// then we need to move back M to that index
else if(p.charAt(i) !== p.charAt(m) && m !== 0) {
m = aux[m-1];
// we dont want to increment I as we want to start comparing this suffix with previous matched
} else {
// if none of the above conditions then
// just update the current index in aux array to 0
aux[i] = 0; // no match
i++; // shift to the next char
}
}
return aux;
}
No offset version
This is based on the idea of what I call todo indexing:
int confix[1000000];
void build_confix(char *pattern) {
// build len %
int len_pat = strlen(pattern);
// i, j using todo-indexing.
int j, i;
confix[j = 1] = i = 0;
while (j < strlen(pattern)) {
whlie (i && pattern[j] != pattern[i])
// length -> length mapping, no offset
i = confix[i];
confix[++j] = pattern[j] == pattern[i]?
++i:
0;
}
}
Then you can use this confix[] table to find needles in the middle(test)
int kmp_find_first(char *test, char *needle) {
int j = 0, i = 0;
while (j < strlen(test)) {
while (i && test[j] != needle[i])
i = confix[i];
++j; test[j] == needle[i]?
++i:
0;
if (i == strlen(needle))
return j - strlen(needle);
}
return -1;
}

Resources