I tried the following code to convert a number from base-10 to another base. it works if there is no zero(0) in the destination base. check 79 and 3 and it properly prints 2221 which is correct.
now try number 19 and 3, the result would be 21 instead of 201 which indicates something's wrong.
int x, y, a = 0, i, t, j;
cout << "enter two numbers" << endl;
cin >> x >> y; // x as the number in base-10 and x, as the destination base
a = x;
while (x >= y)
{
t = 1;
for (i = 0; x > y; i++)
{
x /= y;
}
cout << x;
for (j = 0; j < i; j++)
{
t *= y;
}
a = a - (t*x);
x = a;
}
cout << x<<endl;
Using a recursive function is easier than using a while loop for what you are trying to accomplish.
Here's working program.
#include <iostream>
void printInBase(int x, int y)
{
if ( x < y )
{
std::cout << x;
return;
}
int rem = x%y;
printInBase(x/y, y);
std::cout << rem;
}
int main()
{
int x, y;
std::cout << "enter two numbers" << std::endl;
std::cin >> x >> y; // x as the number in base-10 and x, as the destination base
printInBase(x, y);
std::cout << '\n';
}
int x, y, a = 0, i, t, j;
cout << "enter two numbers" << endl;
cin >> x >> y; // x as the number in base-10 and x, as the destination base
a = x;
t = 1;
while (x >= t*y)
{
t = t * y;
}
while (t)
{
cout << x/t << ' ';
x -= t*(x/t);
t /= y;
}
cout << '\n';
basically you weren't keeping track of what digit you were printing out, and your code can't tell when it would need leading zeroes. You could fix that by printing something like 2*(3^2) + 1*(3^0) or by figuring out how many digits you need in advance as I did in the above code.
Despite it could work, there is something conceptually wrong in this approach: you are essentially confusing numbers (the subject of arithmetic operations) with their textual representation (the sequence of digits used to represent them).
The type int -by an external point of view- does not have a "base" (int will most likely have a base-2 internal representation, that's functional to the purpose to be manipulated by the arithmetic unit circuitry): it's just a thing to be added, subtracted multilyed, divided, and-ed, xor-ed etc.
When you do cout << a what << do, is convert the a number to a sequence of digit representing it into something readable. By default it happens to do it in base-10 digit represented as ASCII characters ('0'...'9').
What you are doing is convert a number into another number whose decimal representation resemble the base you are mapping. It can work in printing, but there is no arithmetic that can work with it. So int is not a correct representation for them.
What you need is a different text-converter: something that takes an int and another int specifying a base, and spits out the characters to represent your number.
Think to a class like
class based
{
int n, base;
public:
based(int num, int base) :n(num), base(base) {}
friend std::ostream& operator<<(std::ostream& out, const based& x);
};
to be used as
std::cout << bsed(79,3) << ' ' << based(19,3) << std::endl;
Now
std::ostream& operator<<(std::ostream& out, const based& x)
{
static const size_t N = 8*sizeof(int)+2; //base 2 is the widest, and is 32 or 64 + 2
char buff[N]; //keep space for sign + base2 + terminator
size_t X = N-1; //current writing character position
buff[X] = 0; //terminating char
--X; //prepare next left character
int n = x.n; //we will work on n
bool neg = (n<0); //keep negative sign
if(neg) n=-n; //and work always with posiotives
while(n) //we will reduce n down to 0
{
int digit = n%x.base; //mod is the last digit
n /= x.base; //next to the left
buff[X] = (digit<10)? char(digit+'0'): char(digit-10+'A');
--X; //next char
}
if(neg) buff[X] = '-';
else ++X; //no sign
out << buff+X << '(' << x.base << ')'; //the text from the point we reach towards left
return out;
}
This will output 2221(3) 201(3).
There is also a more portable way to do char(digit+'0') etc. but considering normal digits, that's not more of what is needed.
My answer.
Will also work on floating point numbers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void radix(char *strNum, int base);
int main ()
{
radix("215.75", 8);
return 0;
}
void swap(char *a, char *b)
{
char temp = *a;
*a = *b;
*b = temp;
}
void radix(char *strNum, int base)
{
char res[100]={0}, tmp[100]={0}, floPoint[100]={0}, *p = 0, *q = 0;
int inum = 0, digitAfterDot = 3;
float fnum = 0.0;
if(strchr(strNum, '.'))
{
p = strNum + strcspn(strNum, ".");
fnum = atof(p);
}
inum = atoi(strNum);
for(p = res; inum; inum /= base, p++)
*p = (inum % base) + '0';
*p = 0;
if(fnum != 0.0)
{
p = floPoint;
*p++ = '.';
for(fnum *= base; digitAfterDot--; p++, fnum *= base)
{
sprintf(tmp, "%f", fnum);
inum = atoi(tmp);
fnum -= inum;
*p = inum + '0';
}
*p = 0;
}
for(p = res, q = res+strlen(res)-1; p < q; p++, q--)
swap(p, q);
strcat(res, floPoint);
puts(res);
}
Related
I have been asked by my teacher to solve this problem: "You get 3 different numbers as input, of different length, you have to determine the sum of the digits of all 3 numbers and also the product"
I solved it like this:
#include <bits/stdc++.h>
using namespace std;
int main () {
int a, b, c, S, P;
cin >> a >> b >> c;
S = 0;
P = 1;
while (a != 0) {
int c1 = a % 10;
S += c1;
P *= c1;
a /= 10;
}
while (b != 0) {
int c1 = b % 10;
S += c1;
P *= c1;
b /= 10;
}
while (c != 0) {
int c1 = c % 10;
S += c1;
P *= c1;
c /= 10;
}
cout << S << ' ' << P << endl;
}
My question is, is there a way to solve this more efficient?
You should bother not about the fastest way that does not make sense for such a simple program but about the correctness of the code and avoiding its duplication.
Your program is just incorrect.
For starters the user can interrupt the input. In this case at least one of the variables a, b, c will have indeterminate value. As a result the program will have undefined behavior.
Secondly, as you are using the signed int type when the user can enter negative numbers. In this case you will get an incorrect result because for example sum of digits can occur to be negative.
Thirdly, the user can enter 0 as a value of a number. In this case this number will be skipped in a while loop like this
while (a != 0) {
In this case you again will get an incorrect result because the product of digits can be not equal to zero though it must be equal to zero in this case.
The same while loops are duplicated. That is the program has a redundant code.
The program can be written the following way as it is shown in the demonstrative program below.
#include <iostream>
int main()
{
long long int a = 0, b = 0, c = 0;
std::cin >> a >>b >> c;
long long int sum = 0;
long long int product = 1;
for ( int num : { a, b, c } )
{
const long long int Base = 10;
do
{
long long int digit = num % Base;
if ( digit < 0 ) digit = -digit;
sum += digit;
if ( product ) product *= digit;
} while ( num /= Base );
}
std::cout << "sum = " << sum << '\n';
std::cout << "product = " << product << '\n';
return 0;
}
Move the repeated code to a separate function.
#include <iostream>
using namespace std;
void calc(int num, int &sum, int &product) {
do {
int c1 = num % 10;
sum += c1;
product *= c1;
num /= 10;
}
while (num != 0);
}
int main () {
int a, b, c, S = 0, P = 1;
if (cin >> a >> b >> c) {
calc(a, S, P);
calc(b, S, P);
calc(c, S, P);
cout << S << ' ' << P << endl;
}
return 0;
}
So, I need to implement TheSameDigit() function, basically this function needs to print out all combinations of numbers that has the same digits. TheSameDigit function MUST be recursive and use NoDigits() and DelDigit() functions.
NoDigits(int x) => This function will return the number of digits
input: 123, output: 3
DelDigit(int x, int delD) => This function return an int which value is x, but having the delD-digit removed.
input: x = 789, delD = 2, output = 79
TheSameDigit() => The function to prints the combination of numbers with the same digits(it does not work currently).
Input: 123
Output:
123
231
132
312
213
321
#include <iostream>
using namespace std;
int NoDigits(int x);
int DelDigit(int x, int delD);
void TheSameDigits(int x, int i, int origin, bool firstTime);
int main() {
int num;
cout << "Please input an integer: ";
cin >> num;
cout << "All integers have the same digits with " << num << " are: " << endl;
TheSameDigits(num, 1, num, 1);
}
int NoDigits(int x) {
if (x == 0) {
return 0;
}
return 1 + NoDigits(x / 10);
}
int DelDigit(int x, int delD) {
int size = NoDigits(x);
int reverse = 0;
for (int i = 0; x != 0; i++, x /= 10) {
if (i != size - delD) {
int digit = x % 10;
reverse = reverse * 10 + digit;
}
}
int newNum = 0;
for (int i = 0; reverse != 0; i++, reverse /= 10) {
int digit = reverse % 10;
newNum = newNum * 10 + digit;
}
return newNum;
}
void TheSameDigits(int x, int i, int origin, bool firstTime) {
const int size = NoDigits(origin);
// Base case
if (origin == x && !firstTime) {
return;
}
if (i == size) {
i = 1;
}
// Find the removed digit
int temp = x;
int removedDigit;
for (int j = 0; temp > 0; j++, temp /= 10) {
if (j == size - i) {
removedDigit = temp % 10;
break;
}
}
// Calculate the next combination
int nextNum = (DelDigit(x, i) * 10) + removedDigit;
cout << nextNum << endl;
TheSameDigits(nextNum, i + 1, origin, false);
}
Can someone help me implement TheSameDigit function or give me an idea about it?
Thank you!
This is what I came up with
#include <iostream>
using namespace std;
int serialNumber = 1;
Would recursion be better?
int factorial(int n)
{
int k=1;
for(int i=1;i<=n;++i)
{
k=k*i;
}
return k;
}
How can I go about doing this in a single for loop?
Or is this the best way?
int main()
{
int a;
int b;
int c;
int fact1;
int fact2;
int fact3;
for (a=1;a < 11;a++)
{
fact1 = factorial(a);
for (b=1;b < 11;b++)
{
fact2 = factorial(b);
for (c=1;c < 11;c++)
{
fact3 = factorial(c);
cout << serialNumber << " : ";
int LHS = fact1 + fact2 + fact3;
if (LHS == a * b * c)
{
cout << "Pass:" <<" "<< a << " & " << b << " & " << c << endl;
}
else
{
cout << "Fail" <<endl;
}
serialNumber++;
}
c = 1;
}
b = 1;
}
return 0;
}
I am being forced to add more none code into it.
Thanks for the help!
Don't know if this is helps,but>
check for minimum of A,B,C
A!+B!+C! = (min(A,B,C)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))
So, you can calculate the minimum factorial and than re-use it for calculating others.
On the other hand, you can calculate only the maximum factorial and store its results in the array, and re-use pre-calculated values for finding factorial of smaller numbers
Other implication is that the minimum number can be reduced
restfact1 * restfact2 = ((min-1)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))
Part of the question was how can this be done in a single loop and this is one way to do that.
I don't think this is a better way of doing it, but the question was asked:
constexpr int bound = 10;
int Factorials[bound + 1];
for (int i = 1; i <= bound; ++i) Factorials[i] = Factorial(i);
for (int i = 0; i < bound * bound * bound; ++i) {
int s = i + 1;
int a = i;
int c = 1 + a % bound;
a /= bound;
int b = 1 + a % bound;
a /= bound;
++a;
cout << s << " : ";
int LHS = Factorials[a] + Factorials[b] + Factorials[c];
if (LHS == a * b * c)
...
}
I have written the code for RSA in C++ on Ubuntu. It was working fine on that, it's working fine on Windows Dev C++ as well, but it doesn't show the character properly.
Here is the code :
#include<iostream>
#include<stdlib.h> // for rand()
#include<math.h> // for floor function
#include<string.h>
using namespace std;
//function to check whether a number is prime or not
int check_prime(int number)
{
int count = 0;
for(int i = 2; i<number + 1; i++)
{
if(number%i == 0)
{
count++;
}
}
if(count>2)
{
return 0;
}
else
{
return 1;
}
}
//function to generate a random prime number
int generate_random_prime()
{
int temp;
while(1)
{
temp = rand() % 50;
if(check_prime(temp) == 1)
{
return temp;
}
}
}
int gcd(int a, int b)
{
int temp;
while(b != 0)
{
temp = b;
b = a%b;
a = temp;
}
return a;
}
// Extended Euclid GCD to find d such de congruent to 1
int extended_gcd(int a, int b)
{
int d, x, y, r, q;
if(b == 0)
{
d = a;
x = 1;
y = 0;
cout << "\n d= " << d << " x= " << x << " y= " << y << "\n";
}
int x2, x1, y2, y1;
x2 = 1;
x1 = 0;
y2 = 0;
y1 = 1;
while(b > 0)
{
q = floor(a / b);
r = a - q*b;
x = x2 - q*x1;
y = y2 - q*y1;
a = b;
b = r;
x2 = x1;
x1 = x;
y2 = y1;
y1 = y;
}
d = a;
x = x2;
y = y2;
return x2;
}
//returns a^b mod n using square and multiply method
int modular_exponentiation(int a, int b, int n)
{
if(a == 1)
{
return 0;
}
int c = 1;
for(int i = 1; i < b + 1; i++)
{
c = (c*a) % n;
}
return c;
}
//cipher text = (message^e) %n
int cipher_text(int m, int e, int n)
{
return modular_exponentiation(m, e, n);
}
//decrypted_text= (cipher^d)%n
int decrypt_cipher(int c, int d, int n)
{
return modular_exponentiation(c, d, n);
}
int main()
{
// generating two random prime p and q
int p = generate_random_prime();
int q = generate_random_prime();
cout << "Prime p : " << p << "and q : " << q << "\n";
int n = p*q;
cout << "n=p*q = " << n << "\n";
//calculating Euler Totient for prime p and q
int euler_phi = (p - 1)*(q - 1);
cout << "Euler totient is : " << euler_phi << "\n";
int d, e;
// calculating e such that 1<e<euler_phi and gcd(n,euler_phi)=1
while(1)
{
e = rand() % (euler_phi - 1 + 1) + 1;
if(gcd(euler_phi, e) == 1)
{
break;
}
}
cout << "e value is : " << e << "\n";
//calculating d such that ed congruent 1, ed=1
d = extended_gcd(e, euler_phi);
//d=5;
cout << "d value is : " << d << "\n";
//storing the message to be encrypted as char array and encrypting each char element
char message[20];
int cipher[20];
cout << "Enter the message to be encrypted : ";
cin >> message;
cout << "Message to be encrypted is : " << message << "\n";
int size = strlen(message);
//calculating cipher text c
for(int i = 0; i < size; i++)
{
cipher[i] = cipher_text(int(message[i]), e, n);
}
cout << "Cipher text is : ";
for(int i = 0; i < size; i++)
{
cout << cipher[i] << " ";
}
char message_decrypted[size];
//decrypting cipher text
for(int i = 0; i < size; i++)
{
message_decrypted[i] = decrypt_cipher(cipher[i], d, n);
}
cout << "\nDecrypted message is : ";
for(int i = 0; i < size; i++)
{
cout << message_decrypted[i];
}
cout << "\n";
return 0;
}
I have tried the code on DevC++ and using g++.
Check the images :
Image using g++ compiler
I need a way to print the char to be displayed properly.
I think that message_decrypted[i]=decrypt_cipher(cipher[i],d,n); needs to be changed to print the character properly in Devcpp
Here is the link to the code in online IDE where it works fine https://repl.it/#shubhamjohar/RSA
When your main routine invokes
decrypt_cipher(cipher[i], d, n);
cipher[0] is 386 as matching your output above. d is -179. And n is 697
The corresponding call into modular_exponentiation(a=386, b=-179, n=697) results in this for-loop getting skipped:
for (int i = 1; i<b + 1; i++) {
c = (c*a) % n;
}
Because i < (b + 1) evaluates to (1 < -178), which evaluates to false.
Therefore, your modular_exponentiation returns 1, which is an unprintable character.
Same applies for the subsequent calls to decrypt_cipher from main.
I don't know enough about the RSA algorithm to know if your implementation is correct. But when d is negative, that for-loop isn't going to do any loops.
Maybe it is incurred by the following expression in your program:
char message_decrypted[size];
There is some standard change related to this usage. please read the following page for more details.
https://www.geeksforgeeks.org/variable-length-arrays-in-c-and-c/
Or try to use something like new char[size] to allocate memory dynamically.
I have an integer:
int iNums = 12476;
And now I want to get each digit from iNums as integer. Something like:
foreach(iNum in iNums){
printf("%i-", iNum);
}
So the output would be: "1-2-4-7-6-".
But i actually need each digit as int not as char.
Thanks for help.
void print_each_digit(int x)
{
if(x >= 10)
print_each_digit(x / 10);
int digit = x % 10;
std::cout << digit << '\n';
}
Convert it to string, then iterate over the characters. For the conversion you may use std::ostringstream, e.g.:
int iNums = 12476;
std::ostringstream os;
os << iNums;
std::string digits = os.str();
Btw the generally used term (for what you call "number") is "digit" - please use it, as it makes the title of your post much more understandable :-)
Here is a more generic though recursive solution that yields a vector of digits:
void collect_digits(std::vector<int>& digits, unsigned long num) {
if (num > 9) {
collect_digits(digits, num / 10);
}
digits.push_back(num % 10);
}
Being that there are is a relatively small number of digits, the recursion is neatly bounded.
Here is the way to perform this action, but by this you will get in reverse order.
int num;
short temp = 0;
cin>>num;
while(num!=0){
temp = num%10;
//here you will get its element one by one but in reverse order
//you can perform your action here.
num /= 10;
}
I don't test it just write what is in my head. excuse for any syntax error
Here is online ideone demo
vector <int> v;
int i = ....
while(i != 0 ){
cout << i%10 << " - "; // reverse order
v.push_back(i%10);
i = i/10;
}
cout << endl;
for(int i=v.size()-1; i>=0; i--){
cout << v[i] << " - "; // linear
}
To get digit at "pos" position (starting at position 1 as Least Significant Digit (LSD)):
digit = (int)(number/pow(10,(pos-1))) % 10;
Example: number = 57820 --> pos = 4 --> digit = 7
To sequentially get digits:
int num_digits = floor( log10(abs(number?number:1)) + 1 );
for(; num_digits; num_digits--, number/=10) {
std::cout << number % 10 << " ";
}
Example: number = 57820 --> output: 0 2 8 7 5
You can do it with this function:
void printDigits(int number) {
if (number < 0) { // Handling negative number
printf('-');
number *= -1;
}
if (number == 0) { // Handling zero
printf('0');
}
while (number > 0) { // Printing the number
printf("%d-", number % 10);
number /= 10;
}
}
Drawn from D.Shawley's answer, can go a bit further to completely answer by outputing the result:
void stream_digits(std::ostream& output, int num, const std::string& delimiter = "")
{
if (num) {
stream_digits(output, num/10, delimiter);
output << static_cast<char>('0' + (num % 10)) << delimiter;
}
}
void splitDigits()
{
int num = 12476;
stream_digits(std::cout, num, "-");
std::cout << std::endl;
}
I don't know if this is faster or slower or worthless, but this would be an alternative:
int iNums = 12476;
string numString;
stringstream ss;
ss << iNums;
numString = ss.str();
for (int i = 0; i < numString.length(); i++) {
int myInt = static_cast<int>(numString[i] - '0'); // '0' = 48
printf("%i-", myInt);
}
I point this out as iNums alludes to possibly being user input, and if the user input was a string in the first place you wouldn't need to go through the hassle of converting the int to a string.
(to_string could be used in c++11)
I know this is an old post, but all of these answers were unacceptable to me, so I wrote my own!
My purpose was for rendering a number to a screen, hence the function names.
void RenderNumber(int to_print)
{
if (to_print < 0)
{
RenderMinusSign()
RenderNumber(-to_print);
}
else
{
int digits = 1; // Assume if 0 is entered we want to print 0 (i.e. minimum of 1 digit)
int max = 10;
while (to_print >= max) // find how many digits the number is
{
max *= 10;
digits ++;
}
for (int i = 0; i < digits; i++) // loop through each digit
{
max /= 10;
int num = to_print / max; // isolate first digit
to_print -= num * max; // subtract first digit from number
RenderDigit(num);
}
}
}
Based on #Abyx's answer, but uses div so that only 1 division is done per digit.
#include <cstdlib>
#include <iostream>
void print_each_digit(int x)
{
div_t q = div(x, 10);
if (q.quot)
print_each_digit(q.quot);
std::cout << q.rem << '-';
}
int main()
{
print_each_digit(12476);
std::cout << std::endl;
return 0;
}
Output:
1-2-4-7-6-
N.B. Only works for non-negative ints.
My solution:
void getSumDigits(int n) {
std::vector<int> int_to_vec;
while(n>0)
{
int_to_vec.push_back(n%10);
n=n/10;
}
int sum;
for(int i=0;i<int_to_vec.size();i++)
{
sum+=int_to_vec.at(i);
}
std::cout << sum << ' ';
}
The answer I've used is this simple function:
int getDigit(int n, int position) {
return (n%(int)pow(10, position) - (n % (int)pow(10, position-1))) / (int)pow(10, position-1);
}
Hope someone finds this helpful!
// Online C++ compiler to run C++ program online
#include <iostream>
#include <cmath>
int main() {
int iNums = 123458;
// int iNumsSize = 5;
int iNumsSize = trunc(log10(iNums)) + 1; // Find length of int value
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
// The pow() function returns the result of the first argument raised to
the power of the second argument.
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d ",z - x2*10 ); // Print Values
}
return 0;
}
You can do it using a while loop and the modulo operators.
It just gives the digits in the revese order.
int main() {
int iNums = 12476;
int iNum = 0;
while(iNums > 0) {
iNum = iNums % 10;
cout << iNum;
iNums = iNums / 10;
}
}
int a;
cout << "Enter a number: ";
cin >> a;
while (a > 0) {
cout << a % 10 << endl;
a = a / 10;
}
int iNums = 12345;
int iNumsSize = 5;
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d-",z - x2*10 );
}