Broken Oven Keypad - c++

The keypad is broken so the input numbers 1, 4, and 7 aren't working. In turn the computer outputs the next lowest and next highest number where 1, 4, and 7 are none of the digits.
My goal is to check out the digits and output true using a boolean function and then output the next highest number and next lowest number. I'm pretty sure I did most of what I need to do, but it isn't working out.
I have inputted the number 444, and the results that came out were 443, and 445.
Thank you for your help.
#include <iostream>
#include <conio.h>
#include <cmath>
using namespace std;
bool containDigit(int number, int digit);
int main()
{
int number, digit, lowNum, highNum;
cout<<"Enter a number between 1 and 999 for the oven temperature: ";
cin>>number;
//1st digit
digit = number / 100;
containDigit(number, digit);
if (containDigit(number, digit) == true)
{
number = number - 100;
}
//2nd digit
digit = (number / 10) % 10;
containDigit(number, digit);
if (containDigit(number, digit) == true)
{
number = number - 10;
}
//3rd Digit
digit = number % 10;
containDigit(number, digit);
if (containDigit(number, digit) == true)
{
number = number - 1;
}
cout<<number<<endl;
getche();
return 0;
}
bool containDigit(int number, int digit)
{
if ((digit == 1) || (digit == 4) || (digit == 7))
{
return true;
}
else
{
return 0;
}
}

The bug is in containDigit function. Try this:
bool containDigit(int number, int digit) {
if(digit == 1 || digit == 4 || digit == 7) return true;
return false;
}
You must use == instead of =.
Also you actually don't need number argument there.
Also there can be done several optimizations. Please look at it yourself (it's your homework) and think about repeated code.

Since this looks like homework, I will refrain from doing it for you and give you these hints:
It looks like you're not really clear on what "1st digit" is. Is it the first one from the left (hundreds) or the right (ones)? Look at your code and tell yourself how each portion of it would answer my question.
Is it ever possible for lowNum or highNum to have more than one digit different than number with your code as it is? How? Where are lowNum and highNum changed, and how?
Also, to expand on what #Al Kepp has said: When you have a function like that, try to test it with some very simple inputs rather than straight out assuming it works. This is called (or is similar to) "unit testing", which dictates that you divide your program into simple, independent units and test them separately. A simple call like containDigit(999, 4) returning true would've rang warning bells.
And speaking of warnings, always, always compile with as many of them as you can stand. (e.g. -Wall for gcc) Doing such might've warned you of the fact that you're not using the parameter number inside containDigit at all.

Your function containDigit has two problems:
It shouldn't need to receive the variable "number" as it doesn't use it
You want to compare with == not =

Related

How to find greater than a number that should be a Fascinating number ,

Fascinating Number:-
Hey find any four digit number fascinating that has all the 4 digits unique. For example 1234 is a fascinating number. His friend Rahul gave him N numbers and asks him to find the minimum number which is strictly larger than the given one and has only distinct digits.
Input format
The first line of the input contains integer N, denoting the count of numbers provided by Rahul.
Each of the next N lines contains one integer.
Output format
Print the next fascinating number.
Constraints
1<=N<=10
1000<=number<=9000
Time Limit
1 second
Example
Input
2
1234
2010
Output
1235
2013
Sample test case explanation, 1235 is the minimum number that is larger than 1234 with all 4 digits 1,2,3,5 distinct.
Please can anyone help, my approach is to take a number from user and find out all the digits and check whether they are equal or not, if they aren't equal then add +1 in the digit.
#include <iostream>
using namespace std;
int main() {
int N,num;
cin>>num;
int first_digit,second_digit,third_digit,fourth_digit;
fourth_digit=num%10;
num=num/10;
third_digit=num%10;
num=num/10;
second_digit=num%10;
num=num/10;
first_digit=num%10;
while (first_digit==second_digit || first_digit==third_digit || first_digit==fourth_digit || second_digit==first_digit||second_digit==third_digit||second_digit==fourth_digit || third_digit==first_digit|| third_digit==second_digit|| third_digit==fourth_digit || fourth_digit==first_digit || fourth_digit==second_digit || fourth_digit==third_digit)
{
if (first_digit == second_digit)
{
second_digit=second_digit+1;
}
else if(first_digit == third_digit)
{
third_digit=third_digit+1;
}
else if(first_digit == fourth_digit)
{
fourth_digit=fourth_digit+1;
}
if (second_digit == first_digit)
{
second_digit=second_digit+1;
}
else if(second_digit == third_digit)
{
third_digit=third_digit+1;
}
else if(second_digit == fourth_digit)
{
fourth_digit=fourth_digit+1;
}
if (third_digit == first_digit)
{
third_digit=third_digit+1;
}
else if(third_digit == second_digit)
{
third_digit=third_digit+1;
}
else if(third_digit == fourth_digit)
{
fourth_digit=fourth_digit+1;
}
if (fourth_digit == first_digit)
{
fourth_digit=fourth_digit+1;
}
else if(fourth_digit == second_digit)
{
fourth_digit=fourth_digit+1;
}
else if(fourth_digit == third_digit)
{
fourth_digit=fourth_digit+1;
}
}
cout<<first_digit<<second_digit<<third_digit<<fourth_digit;
return 0;
}
Their are many mistakes in the code let me point them so you check and try it yourself
Mistakes which i noticed
1.What are u exactly checking in the while condition (your intention is to check weather the number digits are unique or not but when u give a unique input then it will never go inside the while loop)
When their is a digit like 9 when u add 1 to it it becomes 10 and 10 will appended please try other approach when its 9 (hint increase the previous digit by 1 and move that 9 to zero) [example if number is 2039 you code will make it 20310 which is wrong if u try increased the before number which means 2049 and replacing 9 with 0 and again as 0 is duplicate repeat until u get unique numbers]
Hope this explanation helps!
(Remember these things(Few suggestions))
If this question is from a competition of codding post the questions after competition
If you just want direct code from here this is not the correct place!

Error with two credit card numbers. Identifies the number as the wrong credit card type

These are my current errors, I think I did something wrong with the maths but everything I tried didn't work.
Ps: Sorry if my question's formatting is bad, first time using stackflow.
:) credit.c exists
:) credit.c compiles
:) identifies 378282246310005 as AMEX
:) identifies 371449635398431 as AMEX
:) identifies 5555555555554444 as MASTERCARD
:) identifies 5105105105105100 as MASTERCARD
:) identifies 4111111111111111 as VISA
:) identifies 4012888888881881 as VISA
:) identifies 4222222222222 as VISA
:) identifies 1234567890 as INVALID
:) identifies 369421438430814 as INVALID
:) identifies 4062901840 as INVALID
:) identifies 5673598276138003 as INVALID
:( identifies 4111111111111113 as INVALID
expected "INVALID\n", not "VISA\n"
:( identifies 4222222222223 as INVALID
expected "INVALID\n", not "VISA\n"
#include <cs50.h>
#include <math.h>
// Prompt user for credit card number
int main(void)
{
long credit_card, credit_number;
do
{
credit_card = get_long("Enter credit card number: ");
}
while (credit_card < 0);
credit_number = credit_card;
// Calculate total number of digits
int count = (credit_number == 0) ? 1 : (log10(credit_number) + 1);
int summation = 0;
while (credit_number == 0)
{
int x = credit_number % 10; summation += x;
int y = 2 * ((credit_number / 10) % 10);
int r = (y % 10) + floor((y / 10) % 10); summation += r; credit_number /= 100;
}
string card;
// Identify which card type you get after inputing your credit card number
int test = cc / pow(10, count - 2);
if ((count == 13 || count == 16) && test / 10 == 4)
{
card = "VISA";
}
else if (count == 16 && test >= 51 && test <= 55)
{
card = "MASTERCARD";
}
else if (count == 15 && (test == 34 || test == 37))
{
card = "AMEX";
}
else
{
card = "INVALID";
}
// Final verification
if (sum % 10 == 0)
{
printf("%s\n", card);
}
else
{
printf("INVALID\n");
}
}```
Your algorithm is maybe not fully correct. I would therefore propose a different approach. You can look at each single digit in a loop. And, you can also do the whole checksum calculation in one step.
I will show you how to do and explain the algorithm behind it.
BTW. Chosing the right algorithm is always the key for success.
So, first we need to think on how we can extract digits from a number. This can be done in a loop by repeating the follwoing steps:
Perform a modulo 10 division to get a digit
Do a integer division by 10
Repeat
Let us look at the example 1234.
Step 1 will get the 4 -- (1234 % 10 = 4)
Step 2 will convert original number into 123 -- (1234 / 10 = 123)
Step 1 will get the 3 -- (123 % 10 = 3)
Step 2 will convert the previous number into 12 -- (123 / 10 = 12)
Step 1 will get the 2 -- (12 % 10 = 2)
Step 2 will convert the previous number into 1 -- (12 / 10 = 1)
Step 1 will get the 1 -- (1 % 10 = 1)
Step 2 will convert the previous number into 0 -- (1 / 10 = 0)
Then the loop stops. Additionally we can observe that the loop stops, when the resulting divided becomes 0. And, we see addtionally that the number of loop executions is equal to the number of digits in the number. But this is somehow obvious.
OK, then let us look, what we learned so far
while (creditCardNumber > 0) {
unsigned int digit = creditCardNumber % 10;
creditCardNumber /= 10;
++countOfDigits;
}
This will get all digits and count them.
Good. Lets go to next step.
For later validation and comparison purpose we need to get the most significant digit (the first digit) and the second most significant digit (the second digit) of the number.
For this, we define 2 variables which will hold the number. We simply assign the current evaluated digit (and override it in each loop execution) to the "mostSignificantDigit". At the end of the loop, we will have it in our desired variable.
For the "secondMostSignificantDigit" we will simple copy the "old" or "previous" value of the "mostSignificantDigit", before assigning a new value to "mostSignificantDigit". With that, we will always have both values available.
The loop looks now like this:
while (creditCardNumber > 0) {
const unsigned int digit = creditCardNumber % 10;
secondMostSignificantDigit = mostSignificantDigit;
mostSignificantDigit = digit;
creditCardNumber /= 10;
++countOfDigits;
}
OK, now we come to the maybe more complex part. The cheksum. The calculation method is.
Start with the least significant (the last) digit
Do not multiply the digit, which is equivalent with multiplying it with 1, and add it to the checksum
Goto the next digit. Multiply it by 2. If the result is greater than 10, then get again the single digits and add both digits to the checksum
Repeat
So, the secret is, to analyze the somehow cryptic specification, given here. If we start with the last digit, we do not multiply it, the next digit will be multiplied, the next not and so on and so on.
To "not multiply" is the same as multiplying by 1. This means: In the loop we need to multiply alternating with 1 or with 2.
How to get alternating numbers in a loop? The algorithm for that is fairly simple. If you need alternating numbers, lets say, x,y,x,y,x,y,x..., Then, build the sum of x and y and perform the subtratcion "value = sum - value". Example:
We need alternating values 1 and 2. The sum is 3. To get the next value, we subtract the current value from the sum.
initial value = 1
sum = 3
current value = initial value = 1
next value = 3 - 1 = 2. Current value = 2
next value = 3 - 2 = 1. Current value = 1
next value = 3 - 1 = 2. Current value = 2
next value = 3 - 2 = 1. Current value = 1
next value = 3 - 1 = 2. Current value = 2
next value = 3 - 2 = 1. Current value = 1
. . .
Good, now we understand, how to make alternating values.
Next, If we multiply a digit with 2, then the maximum result maybe a 2 digit value. We get the single digits with a modulo and an integer division by 10.
And, now important, it does not matter, if we multiply or not, because, if we do not multiply, then the upper digit will always be 0. And this will not contribute to the sum.
With all that, we can always do a multiplication and always split the result into 2 digits (many of them having the upper digit 0).
The result will be:
checkSum += (digit * multiplier) % 10 + (digit * multiplier) / 10;
multiplier = 3 - multiplier;
An astonishingly simple formula.
Next, if we know C or C++ we also know that a multiplication with 2 can be done very efficiently with a bit shift left. And, additionally, a "no-multiplication" can be done with a bit shift 0. That is extremely efficient and faster than multiplication.
x * 1 is identical with x << 0
x * 2 is identical with x << 1
For the final result we will use this mechanism, alternate the multiplier between 0 and 1 and do shifts.
This will give us a very effective checksum calculation.
At the end of the program, we will use all gathered values and compare them to the specification.
Thsi will lead to:
int main() {
// Get the credit card number. Unfortunately I do not know CS50. I use the C++ standard iostream lib.
// Please replace the following 4 lines with your CS50 equivalent
unsigned long long creditCardNumber;
std::cout << "Enter credit card number: ";
std::cin >> creditCardNumber;
std::cout << "\n\n";
// We need to count the number of digits for validation
unsigned int countOfDigits = 0;
// Here we will calculate the checksum
unsigned int checkSum = 0;
// We need to multiply digits with 1 or with 2
unsigned int multiplier = 0;
// For validation purposes we need the most significant 2 digits
unsigned int mostSignificantDigit = 0;
unsigned int secondMostSignificantDigit = 0;
// Now we get all digits from the credit card number in a loop
while (creditCardNumber > 0) {
// Get the least significant digits (for 1234 it will be 4)
const unsigned int digit = creditCardNumber % 10;
// Now we have one digit more. In the end we will have the number of all digits
++countOfDigits;
// Simply remember the most significant digits
secondMostSignificantDigit = mostSignificantDigit;
mostSignificantDigit = digit;
// Calculate the checksum
checkSum += (digit << multiplier) % 10 + (digit << multiplier) / 10;
// Multiplier for next loop
multiplier = 1 - multiplier;
creditCardNumber /= 10;
}
// Get the least significant digit of the checksum
checkSum %= 10;
// Validate all calculated values and show the result
if ((0 == checkSum) && // Checksum must be correct AND
(15 == countOfDigits) && // Count of digits must be correct AND
((3 == mostSignificantDigit) && // Most significant digits must be correct
((4 == secondMostSignificantDigit) || (7 == secondMostSignificantDigit)))) {
std::cout << "AMEX\n";
}
else if ((0 == checkSum) && // Checksum must be correct AND
(16 == countOfDigits) && // Count of digits must be correct AND
((5 == mostSignificantDigit) && // Most significant digits must be correct
((secondMostSignificantDigit > 0) && (secondMostSignificantDigit < 6)))) {
std::cout << "MASTERCARD\n";
}
else if ((0 == checkSum) && // Checksum must be correct AND
((16 == countOfDigits) || (13 == countOfDigits)) && // Count of digits must be correct AND
((4 == mostSignificantDigit))) { // Most significant digit must be correct
std::cout << "VISA\n";
}
else {
std::cout << "INVALID\n";
}
return 0;
}
What we learn with this example, is integer division and modulo division and the smart usage of the identity element for binary operations.
In case of questions, please ask
Just to be complete, I will show you a C++ solution, based on a std::string and using modern C++ elements and algorithms.
For example, the whole checksum calculation will be done with one statement. The whole program does not contain any loop.
#include <iostream>
#include <string>
#include <regex>
#include <numeric>
int main() {
// ---------------------------------------------------------------------------------------------------
// Get user input
// Inform user, what to do. Enter a credit card number. We are a little tolerant with the input format
std::cout << "\nPlease enter a credit card number:\t";
// Get the number, in any format from the user
std::string creditCardNumber{};
std::getline(std::cin, creditCardNumber);
// Remove the noise, meaning, all non digits from the credit card number
creditCardNumber = std::regex_replace(creditCardNumber, std::regex(R"(\D)"), "");
// ---------------------------------------------------------------------------------------------------
// Calculate checksum
unsigned int checksum = std::accumulate(creditCardNumber.rbegin(), creditCardNumber.rend(), 0U,
[multiplier = 1U](const unsigned int sum, const char digit) mutable -> unsigned int {
multiplier = 1 - multiplier; unsigned int value = digit - '0';
return sum + ((value << multiplier) % 10) + ((value << multiplier) / 10); });
// We are only interested in the lowest digit
checksum %= 10;
// ---------------------------------------------------------------------------------------------------
// Validation and output
if ((0 == checksum) && // Checksum must be correct AND
(15 == creditCardNumber.length()) && // Count of digits must be correct AND
(('3' == creditCardNumber[0]) && // Most significant digits must be correct
(('4' == creditCardNumber[1]) || ('7' == creditCardNumber[1])))) {
std::cout << "AMEX\n";
}
else if ((0 == checksum) && // Checksum must be correct AND
(16 == creditCardNumber.length()) && // Count of digits must be correct AND
(('5' == creditCardNumber[0]) && // Most significant digits must be correct
((creditCardNumber[1] > '0') && (creditCardNumber[1] < '6')))) {
std::cout << "MASTERCARD\n";
}
else if ((0 == checksum) && // Checksum must be correct AND
((16 == creditCardNumber.length()) || (13 == creditCardNumber.length())) && // Count of digits must be correct AND
(('4' == creditCardNumber[0]))) { // Most significant digit must be correct
std::cout << "VISA\n";
}
else {
std::cout << "INVALID\n";
}
return 0;

How do i find GCD with while loop? How does modulus operator work?

#include <iostream>
int GCD()
{
int a,b,k;
cout<<"Enter a and b"<<endl;
cin>>a>>b;
cout<<endl;
if (a>b)
{
k=a;
}
else
{
k=b;
}
cout<<k<<endl;
do
{
k=k-1;
} while(a%k !=0 && b%k !=0);
cout<<k<<endl;
return 0;
}
Why programm like this doesnt work correctly? For example when i enter 125 and 5 answer is 25, but supposed to be 5? Am wrong with logic in while loop? As i understood problem is in modulus operator. When k hits 25 it says that 125%25=0 and 5%=25=0. How can i fix this?
You have some mistakes here:
The GCD is lower or equal to the lower number. Currently, you start checking with the larger number. You need to flip the if block to if (a<b). (not exactly an error, but you check much more numbers than needed)
You need to check if the inital k is the GCD. When using a do {} while() the first number you check is k-1. Use a simple while instead. Also the loop condition has a logic flaw.
while (!((a % k == 0) && (b % k == 0)))
{
k--;
}
Note that the brackets around the modulo are not neccessary, but improve readability a bit.
Your code will not compile under all compilers and you should not omit the namespace std::.
Your while statement has logic error. It needs to be
while(!(a%k == 0 && b%k == 0));
When k is equal to 25, 125%25==0 so in your while statement a%k !=0 part is equals to false so it exit your do-while but it needs to test if b%k is equal to 0 or not!
Also your implementation tends to execute slow when a and b is big. You can take a look efficent solutions.

Test if numbers are divisible by 4, up to 100 digits

Simply enough, I practice programming via an online judge. This is a rather stupid problem, really easy. However, The judge keeps saying I have a wrong answer. I'm just going to paste the code which is just a few lines, and a link to the problem.
#include <iostream>
#include <string>
using namespace std;
int main() {
int cases = 0;
string solution = "";
cin >> cases;
if (cases > 100)
return(0);
for (int i = 0; i < cases; i++) {
int temp = 0;
cin >> temp;
if ((temp % 4) == 0)
solution +="Y";
else
solution +="N";
}
for (int j = 0; j < cases; j++) {
if (solution[j] == 'Y')
cout << "YES";
else
cout << "NO";
cout << endl;
}
}
The problem is simply to output YES or NO for each number that is input that is divisible by 4, YES for if it is, NO if its not. The problem and every minute detail can be found: http://coj.uci.cu/24h/problem.xhtml?abb=1306
This is rather silly, but I'm going bonkers here trying to figure out what I'm doing WRONG!
A number is divisible by 4 if its two last decimal digits are divisible by 4.
The end.
P.S. Sometimes it makes sense to stop thinking as a programmer and remember algebra/arithmetics.
As I said in a comment, the problem is that you cannot read a 100 digit number into an int directly. I don't want to give you the solution to the algorithm, but a hint that should help: How many digits would you need to know if the number was divisible by 2 or by 5? And how could you extend that to 4?
If you express a number X as Y + d where d = X%100 and Y = X -d we can see that Y will always be divisible by 100, for example for the number X = 343535, Y would be 343500 and d would be 35. Since Y is divisible by 100, implies that is divisible by 4, so you can determinate if X is divisible by 4, checking if d is divisible by 4, i.e the last two digits of X.
Formally it would be:
Y = 4*Z
Y = 100*X +d
Y = 4*Z = 4*25*X +d
d = 4*(Z - 25*X)
i.e if Y is multiple of 4, d is multiple of 4
You have to apply this principle to solve your problem.
Simply read a raw string and check if the number represented by the last two characters are divisible by four.
As tempting as might be, you don't need a BitInteger to figure out whether a 100 digit number, of 1 million digit number is divisible by 4. That's just simple math, that you should be able to figure by yourself in a minute, if you don't know the rule.
Perhaps the problem is this if (cases > 100). because of this -1 would be a valid option.
Change to if (cases > 100 && cases < 1) to fix it
I wouldn't even read the whole number. I would just read the last 2 digits before the EOF char (end of file).
string inputString;
while(getline(cin,inputString)
{
//code for finding x %4==0 and output
}
then all you need to do is convert the last 2 chars into a int and then do your mod 4 code. (you'll need a catch value for numbers < 10, but that shouldn't be hard)

Define function to find the last even digit using recursion

Suppose input no is f(354683257) returns 2.
It sounds like you can break this into two easier problems.
How do you find the last digit of a given number?
How do you strip off the last digit of a given number?
Here's my solution. However, what are you supposed to do if there are no even digits in the number?
int findLastEvenDigit(int n)
{
lastDigit = n % 10;
if (lastDigit % 2 == 0) return lastDigit;
else return findLastEvenDigit(n/10);
}
Assumptions: No negative numbers (not sure/relevant if it will work for them)