So I am trying to encrypt a four digit integer by adding seven to the digit then dividing the whole digit by ten. In my program I am taking each single digit separately and then I need to divide the whole digit by ten. How can I combine all the separate int into one four digit number?
#include "stdafx.h"
using namespace std;
int main()
{
//Define all variables needed
int a,b,c,d,enc,ext;
//Print dialog and input each single digit for the four number digit
cout << "Enter Your First Digit:" << endl;
cin >> a;
cout << "Enter Your Second Digit:" << endl;
cin >> b;
cout << "Enter Your Third Digit:" << endl;
cin >> c;
cout << "Enter Your Fourth Digit:" << endl;
cin >> d;
//Add seven to each digit
a += 7;
b += 7;
c += 7;
d += 7;
a /= 10;
b /= 10;
c /= 10;
d /= 10;
cout << "Your encrpyted digits:" << c << d << a << b <<endl;
cout << "Enter 1 to exit:" <<endl;
cin >> ext;
if (ext = 1) {
exit(EXIT_SUCCESS);
}
}
As you probably noticed I am dividing each number separately. I need to do them together. Then I am also creating a decrypting which I will get me back to the original number in a separate program.
Based on your comment you are trying to do a variation on the Caesar Cipher, in which case you should be using the modulus operator (%) not the integer division operator (/). Using integer division loses information which will prevent you from decrypting. When your digit is in {0, 1, 2} your division results in a 0. When it is in {3, 4, 5, 6, 7, 8, 9}, the division results in a 1. You can't decrypt {0, 1} back into the original number without some additional information (which you have discarded).
If you want to encrypt on a digit by digit basis using the Caesar Cipher approach, you should be using modulo arithmetic so that each digit has a unique encrypted value which can be retrieved during decryption. If that's really what you are looking for then you should be doing something like the following to encrypt with a 7:
a = (a + 7) % 10;
b = (b + 7) % 10;
c = (c + 7) % 10;
d = (d + 7) % 10;
To decrpyt, you subtract 7, which in mod 10 arithmetic is an addition by 3, so that would be:
a = (a + 3) % 10;
b = (b + 3) % 10;
c = (c + 3) % 10;
d = (d + 3) % 10;
This of course presupposes you've properly validated your input (which isn't the case in your example above).
Combining the individual digits into one four-digit number is simple; just multiple the first digit by 1000, add the second multiplied by 100, and so on.
But this is a one-way algorithm; you will never be able to retrieve the original four-digit number from this.
This is what youd'd probably be looking for :
int e = (a*1000)+(b*100)+(c*10)+d;
e=e/10;
It's not clear from your description whether the addition should be modulo 10 or not; if so
((((((a % 10) * 10) + (b % 10)) * 10) + (c % 10)) * 10) + (d % 10)
if you don't want the modulo 10
(((((a * 10) + b) * 10) + c) * 10) + d
Stepping aside the fact that you almost certainly want mod instead of divide (as #Andand has said), there's more than one way to turn the digits into a number!
A lot of people using interpreted languages these days would probably want to do it symbolically. C++ can do that too, fairly neatly in fact:
// create a string stream that you can write to, just like
// writing to cout, except the results will be stored
// in a string
stringstream ss (stringstream::in | stringstream::out);
// write the digits to the string stream
ss << a << b << c << d;
cout << "The value stored as a string is " << ss.str() << endl;
// you can also read from a string stream like you're reading
// from cin. in this case we are reading the integer value
// that we just symbolically stored as a character string
int value;
ss >> value;
cout << "The value stored as an integer is " << value << endl;
It won't be as efficient as multiplications in this narrow case of a 4 digit number, because of the round trip to a string and back. But good to know the technique. Also it's a style of coding that can be a lot easier to maintain and adapt.
You'll get stringstream if you #include <sstream>.
Related
I am trying to take a user entered integer (positive or negative) and let them pick a digit position and output the digit at that position.
int findDigAtPos(int number)
{
int position;
int result;
cout << "Enter digit position between 1 and " << std::to_string(number).length() << endl;
cin >> position;
while (position < 0 || position > std::to_string(number).length())
{
cout << "Enter digit position between 1 and "<< std::to_string(number).length()<<endl;
cin >> position;
}
if (std::to_string(number).length() == 1)
cout << "Only one digit" << endl;
number = number / pow(10, (position - 1.0));
result = number % 10;
return result;
}
This is the code I currently have for the function. However, it outputs the number in reverse. How do I correct the digit position? I thought it didn't even function correctly until noticing it's in reverse order.
First, note that you shouldn't be using the pow function when working with integers, because it returns a double result, which can cause problems due to unexpected truncation of the result.
But, if you insist on using it, then you need to remember that the power of 10 by which to divide will decrease as the digit position increases: i.e., the position is given with the leftmost (most significant) digit in position 1. Thus, that power of 10 will be total number of digits minus the position:
number = number / pow(10, (std::to_string(number).length() - position));
result = number % 10;
The safer method (not using pow) would be a small loop, like this:
for (int d = std::to_string(number).length() - position; d > 0; --d) number /= 10;
result = number % 10;
However, as you're already converting the passed number to a string, then why not just save that string and extract the digit from it – at position-1, because array (and string) indexes in C++ are zero-based:
int findDigAtPos(int number)
{
int position;
std::string str = std::to_string(std::abs(number)); // If -ve, remove sign!
int ndig = str.length();
std::cout << "Enter digit position between 1 and " << ndig << "\n";
std::cin >> position;
while (position < 0 || position > ndig) {
std::cout << "Enter digit position between 1 and " << ndig << "\n";
std::cin >> position;
}
return str.at(position-1) - '0';
}
Note that the codes (ASCII or otherwise) for the numeric digits, 0 thru 9 are guaranteed by the C++ standard to be contiguous and in order, so subtracting the value of the digit 0 will 'convert' any digit to its actual, numerical value.
Instead of this:
number = number / pow(10, (position - 1.0));
result = number % 10;
This:
int length = (int)(std::to_string(number).length());
while (position < length)
{
number = number / 10;
length--;
}
result = number % 10;
The above should work fine for positive numbers. For negative numbers, you might need to a fixup. I'll leave that as an exercise for you to manage.
Sorry if this is a dumb question, this is my first coding class.
If the checksum is 10, the last digit is denoted as X according to the
ISBN-10 convention. Write a program that prompts the user to enter the
first 9 digits and displays the 10-digit ISBN (including leading
zeros). Your program should read the input as an integer.
A sample run should look something like this:
Enter the first nine digits of the ISBN: 013601267
The ISBN-10 number is: 0136012671
I have successfully made a program that can do this but using int value for all nine numbers. Unfortunately, this required the user to input every number separately.
So what I am trying to do now is use use a string ISBN so that I can target individual sections ie. isbn[0] * 1 + isbn[1] * 2...
I have also tried static_cast<char>(ISBN[0]) * 1 + static_cast<char>.... thinking it would do something and I get the same results.
string ISBN;
cout << "Enter the first nine digits of the ISBN as integer: ";
cin>>ISBN;
int n10 = (ISBN[0] * 1 + ISBN[1] * 2 + ISBN[2] * 3 + ISBN[3] * 4 + ISBN[4] * 5 + ISBN[5] * 6 + ISBN[6] * 7 + ISBN[7] * 8 + ISBN[8] * 9) % 11;
if (n10 == 10)
{
cout << ISBN << "X" << endl;
}
else
{
cout << ISBN << n10 << endl;
}
So when I input this number 013601267 I should get a 1 (0136012671) at the end instead I am getting a 5 (0136012675).
I think this is happening because it is giving me ASCII dec value instead of the char value.
Four things you should check:
1: The size of the string is actually 9 characters.
if (ISBN.size() != 9) {
// Error
}
Otherwise accessing elements that do not exist will cause an error in your program.
2: The digits do not start at value 0. In ASCII (or UTF-8) the digits start at 48. Therefore 48 => '0' 49 => '1' etc. But C++ guarantees all the digits are contiguous so as long as you know the first one you can subtract that and get a correct value. If you use '0' in an integer expression it will convert to the correct value. Thus to generate a number value from a char you should subtract this value from each digit before multiplying.
n10 = ((ISBN[0] - '0') * 1) + ((ISBN[1] - '0') * 2) + ...
3: But you should check the string is all digits.
for(auto x: ISBN) {
if (!std::is_digit(x)) {
// ERROR
}
}
4: To print a string of 9 characters with leading zero you need to make sure you prep the stream coreectly:
std::cout << std::setw(9) << std::setfill('0') << number;
Or if the number is already in a string form that you know is 9 characters long you can simply use:
std::cout << ISBN;
So To output the correct 10 character number in your case:
std::cout << ISBN << ((n10 == 10) ? 'X' : ('0' + n10)) << "\n";
First you should check the size of string
if(ISBN.size() != 9){
// ERROR
}
You can use for to calculate 'n10'
int n10 = 0;
for(int i = 0; i < ISBN.size(); ++i){
if(std::is_digit(x)){ // check digit
// characters '0','1','2'... are not same as digits 0, 1, 2...
// the value of '0' is 48, as shown here [ascii table][1]
n10 = (ISBN[i] - '0') * (i+1) + n10;
} else {
// ERROR
}
}
I'm trying a lab exercise which wants user to input a 2 4-digit integer. Then the program will extract all the numbers in the 4-digit integer and use the number to do an arithmetic calculation just like the image link below.
Arithmetic Calculation with 2 4-digit integer
However, the objective for this lab exercise is not to allow me myself, to use a for loop to obtain the result.
For instance, when i want to obtain the last number of the 4 digit integer, I could easily do it by using this.
int firstDigit = firstNo % 10; //i will get 4 if the integer is 1234
int secondDigit = secondNo % 10; //i will get 8 if the integer is 5678
And of course table formatting is nothing to worry about before getting the logic right. Next is a very simple calculation of the numbers using the digit i obtain from the above.
int addfirstNumbers = firstDigit + secondDigit;
int minusfirstNumbers = firstDigit - secondDigit;
int multiplefirstNumbers = firstDigit * secondDigit;
int modfirstNumbers = firstDigit % secondDigit;
double divfirstNumbers = firstDigit / secondDigit;
cout << "add: " << addfirstNumbers << endl
<< "minus " << minusfirstNumbers << endl
<< "multipile " << multiplefirstNumbers << endl
<< "remainder " << modfirstNumbers << endl
<< "division " << divfirstNumbers << endl;
I do understand forloop can make my life easier. But i'm just trying out the long method before trying out the shorter way which is forloop.
But even before i proceed, I'm still unable to extract out the other digit from this 4 digit integer.
Like Mike Vine mentioned in the comments, you can do integer division before taking the modulo.
#include <iostream>
int main(){
int x = 1234;
std::cout << (x/10)%10 << "\n";
}
#Output
3
Edit: This works for all places of a number. To find the nth value from the end, just keep adding 0s to the divisor. For example to find the 2nd from the last, you'd want to divide x by 100 instead.
You could simply do
int secondLastDigit = ((i - (i % 10)) % 100)) / 10;
For i=5678:
i % 10 (5678 % 10) equals 8
i - (i % 10) (5678 - 8) therefore equals 5670.
(i - (i % 10)) % 100 (5670 % 100) equals 70
Finally (i - (i % 10)) % 100) / 10 (70 / 10) = 7
This is pretty simple, just use the modulus operator on the number for 100(num%100), getting the last two digits that way, and then divide that result by ten, and store the digit in an int (so the decimal is properly truncated.)
My code here finds the sum of some given multiples less than or equal to a certain number. It uses a modified version of a formula I read about on the internet a while ago (the one for finding the sum of all the numbers less than or equal to 100, or 1000 or something- when I wrote my formula while I was waiting to be picked up at the ymca so it might not look like the one from the internet). So for me I used (n+x)(n/x/2), where n is the limit (for example 1000), and x is the multiple you are using (so 1, or 3, or 5). So if n = 1000 and x = 5, it should find the sum of all multiples of 5 less than or equal to 1000).
Sometimes it adds up correctly and sometimes it doesn't.
For example, if I choose 1 and 2 as the multiples, and 20 as the limit, it prints out 320 (which is correct if you add 1+2+3...+20 and then add to that 2+4+6...+20).
But if I do the multiples of 3 and 5 and 1000 as the limit, it prints out 266,998 (which is wrong according to the internet).
I do not understand why it worked in the first instance but not the second (I have only taken 1 year of high school math, I'll be a sophomore).
Here is the code:
/*
Finds the sum of all inputted multiples below a certain number
For example, it could find the sum of all the multiples of 3 and 5 less than
or equal to 1000
Written By Jay Schauer
*/
//Data Declarations
#include <iostream>
int main()
{
using namespace std;
int a; //Stores the number of multiples being used
cout << "Enter the amount of multiples you would like to use (up to 50
<< endl;
cout << "(for example, enter '2' if you would like to use two multiples,
maybe 3 and 5?)" << endl;
cin >> a;
cout << "Next, you will enter the mutliples you want to use." << endl;
cout << "(for example, if you want to find the sum of the multiples of 3
and\n5 below a given amount, enter 3 as 'multiple 1' and 5 as 'multiple
2')" << endl;
int multiples[50]; //Stores the multiples being used
for (int i = 0; i < a; i++)
{
cout << "Enter 'multiple " << (i + 1) << "'" << endl;
cin >> multiples[i];
}
int limit; //Stores the limit
cout << "Enter the the limit for how high you want to add the multiples
<< endl;
cout << "(for example, you could set the limit to 1000 to find the sum
of the\nmultiples of 3 and 5 (if you entered those) less than and or
equal to 1000)" << endl;
cin >> limit;
int sum(0); //Stores the sum
for (int i = 0; i < a; i++)
{
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
}
cout << "The sum is "<< sum << endl;
system("pause");
return 0;
}
EDIT: I believe the problem might lie in the code not in the formula, because using it on multiples of 3 with 21 as the limit causes it to print out 72, not 84 like it should. I am still unsure of the coding error.
EDIT 2: I changed the for loop to this so it hopefully will function when the limit isn't a multiple of the multiple
for (int i = 0; i < a; i++)
{
int max = limit; /*This is done so I can change max in case it isn't
a multiple of the multiple*/
while (max % multiples[i] != 0) max--;
sum += ((max + multiples[i]) * (max / multiples[i] / 2));
}
Change
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
to
sum += (limit + multiples[i]) * (limit / multiples[i]) / 2;
As it is, for your example of 3 and 21, you're computing (24 * (7 / 2)) = 24 * 3 = 72 (integer division of 7 by 2 gives 3, and the remainder is lost), but you want to be computing (24 * 7) / 2 = 84.
Whilst working on a personal project of mine, I came across a need to divide two very large arbitrary numbers (each number having roughly 100 digits).
So i wrote out the very basic code for division (i.e., answer = a/b, where a and b are imputed by the user)and quickly discovered that it only has a precision of 16 digits! It may be obvious at this point that Im not a coder!
So i searched the internet and found a code that, as far as i can tell, uses the traditional method of long division by making a string(but too be honest im not sure as im quite confused by it). But upon running the code it gives out some incorrect answers and wont work at all if a>b.
Im not even sure if there's a better way to solve this problem than the method in the code below!? Maybe there's a simpler code??
So basically i need help to write a code, in C++, to divide two very large numbers.
Any help or suggestions are greatly appreciated!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std; //avoids having to use std:: with cout/cin
int main (int argc, char **argv)
{
string dividend, divisor, difference, a, b, s, tempstring = ""; // a and b used to store dividend and divisor.
int quotient, inta, intb, diff, tempint = 0;
char d;
quotient = 0;
cout << "Enter the dividend? "; //larger number (on top)
cin >> a;
cout << "Enter the divisor? "; //smaller number (on bottom)
cin >> b;
//making the strings the same length by adding 0's to the beggining of string.
while (a.length() < b.length()) a = '0'+a; // a has less digits than b add 0's
while (b.length() < a.length()) b = '0'+b; // b has less digits than a add 0's
inta = a[0]-'0'; // getting first digit in both strings
intb = b[0]-'0';
//if a<b print remainder out (a) and return 0
if (inta < intb)
{
cout << "Quotient: 0 " << endl << "Remainder: " << a << endl;
}
else
{
a = '0'+a;
b = '0'+b;
diff = intb;
//s = b;
// while ( s >= b )
do
{
for (int i = a.length()-1; i>=0; i--) // do subtraction until end of string
{
inta = a[i]-'0'; // converting ascii to int, used for munipulation
intb = b[i]-'0';
if (inta < intb) // borrow if needed
{
a[i-1]--; //borrow from next digit
a[i] += 10;
}
diff = a[i] - b[i];
char d = diff+'0';
s = d + s; //this + is appending two strings, not performing addition.
}
quotient++;
a = s;
// strcpy (a, s);
}
while (s >= b); // fails after dividing 3 x's
cout << "s string: " << s << endl;
cout << "a string: " << a << endl;
cout << "Quotient: " << quotient << endl;
//cout << "Remainder: " << s << endl;
}
system ("pause");
return 0;
cin.get(); // allows the user to enter variable without instantly ending the program
cin.get(); // allows the user to enter variable without instantly ending the program
}
There are much better methods than that. This subtractive method is arbitrarily slow for large dividends and small divisors. The canonical method is given as Algorithm D in Knuth, D.E., The Art of Computer Programming, volume 2, but I'm sure you will find it online. I'd be astonished if it wasn't in Wikipedia somewhere.