Appending a number to a number? - c++

How cold I do the following:
say I have the number 10 and would like to append the number 317 to it. The resulting integer would be 10317. How can this be done. Also, once I have this number, how could I then for example remove the 17 off the end. Without using strings, and without obvious solving and adding.
Thanks

This will append both numbers
int append_a_and_b_as_int(int a, int b)
{
for(int tmp = b; tmp > 0; tmp % 10)
{
a *= 10;
}
return a + b;
}
This will get rid of the last n numbers
int remove_n_numbers_from_a(int n, int a)
{
for(int i = 0; i < n; i++)
{
a /= 10;
}
return a;
}

Appending :
int foo(int a, int b)
{
return a*pow(10, floor(log10(b))+1)+b;
}
Removing :
int bar(int a, int b)
{
return a/pow(10, floor(log10(b))+1);
}

For the first one:
int a = 10;
int b = 317;
int result = a * 1000 + b;
For the second:
int result2 = result / 100;

If this is something you need to do in your workplace I'd advise quitting.
You can treat your two numbers as numeric data and solve the question, or you can treat them as strings and use an append.

Related

C++ combination function always resulting 0

can anybody tell me why my Combination function is always resulting 0 ?
I also tried to make it calculate the combination without the use of the permutation function but the factorial and still the result is 0;
#include <iostream>
#include <cmath>
using namespace std;
int factorial(int& n)
{
if (n <= 1)
{
return 1;
}
else
{
n = n-1;
return (n+1) * factorial(n);
}
}
int permutation(int& a, int& b)
{
int x = a-b;
return factorial(a) / factorial(x);
}
int Combination(int& a, int& b)
{
return permutation(a,b) / factorial(b);
}
int main()
{
int f, s;
cin >> f >> s;
cout << permutation(f,s) << endl;
cout << Combination(f,s);
return 0;
}
Your immediate problem is that that you pass a modifiable reference to your function. This means that you have Undefined Behaviour here:
return (n+1) * factorial(n);
// ^^^ ^^^
because factorial(n) modifies n, and is indeterminately sequenced with (n+1). A similar problem exists in Combination(), where b is modified twice in the same expression:
return permutation(a,b) / factorial(b);
// ^^^ ^^^
You will get correct results if you pass n, a and b by value, like this:
int factorial(int n)
Now, factorial() gets its own copy of n, and doesn't affect the n+1 you're multiplying it with.
While we're here, I should point out some other flaws in the code.
Avoid using namespace std; - it has traps for the unwary (and even for the wary!).
You can write factorial() without modifying n once you pass by value (rather than by reference):
int factorial(const int n)
{
if (n <= 1) {
return 1;
} else {
return n * factorial(n-1);
}
}
Consider using iterative code to compute factorial.
We should probably be using unsigned int, since the operations are meaningless for negative numbers. You might consider unsigned long or unsigned long long for greater range.
Computing one factorial and dividing by another is not only inefficient, it also risks unnecessary overflow (when a is as low as 13, with 32-bit int). Instead, we can multiply just down to the other number:
unsigned int permutation(const unsigned int a, const unsigned int b)
{
if (a < b) return 0;
unsigned int permutations = 1;
for (unsigned int i = a; i > a-b; --i) {
permutations *= i;
}
return permutations;
}
This works with much higher a, when b is small.
We didn't need the <cmath> header for anything.
Suggested fixed code:
unsigned int factorial(const unsigned int n)
{
unsigned int result = 1;
for (unsigned int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
unsigned int permutation(const unsigned int a, const unsigned int b)
{
if (a < b) return 0;
unsigned int result = 1;
for (unsigned int i = a; i > a-b; --i) {
result *= i;
}
return result;
}
unsigned int combination(const unsigned int a, const unsigned int b)
{
// C(a, b) == C(a, a - b), but it's faster to compute with small b
if (b > a - b) {
return combination(a, a - b);
}
return permutation(a,b) / factorial(b);
}
You dont calculate with the pointer value you calculate withe the pointer address.

Integer value assignment in c++

I'm pretty new to C++ and I have the following simple program:
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
cout << sum; // outputs 15
return 0;
}
I receive always the output 15, although I've changed the value of b to 6.
Thanks in advance for your answers!
Execution of your code is linear from top to bottom.
You modify b after you initialize sum. This modification doesn't automatically alter previously executed code.
int sum = a + b; writes the result of adding a and b into the new variable sum. It doesn't make sum an expression that always equals the result of the addition.
There are already answers, but I feel that something is missing...
When you make an assignment like
sum = a + b;
then the values of a and b are used to calculate the sum. This is the reason why a later change of one of the values does not change the sum.
However, since C++11 there actually is a way to make your code behave the way you expect:
#include <iostream>
int main() {
int a = 5,b = 10;
auto sum = [&](){return a + b;};
b = 6;
std::cout << sum();
return 0;
}
This will print :
11
This line
auto sum = [&](){return a + b;};
declares a lambda. I cannot give a selfcontained explanation of lambdas here, but only some handwavy hints. After this line, when you write sum() then a and b are used to calculate the sum. Because a and b are captured by reference (thats the meaning of the &), sum() uses the current values of a and b and not the ones they had when you declared the lambda. So the code above is more or less equivalent to
int sum(int a, int b){ return a+b;}
int main() {
int a = 5,b = 10;
b = 6;
std::cout << sum(a,b);
return 0;
}
You updated the b value but not assigned to sum variable.
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
sum = a + b;
cout << sum; // outputs 11
return 0;
}

Multiplying a digit of a number with its current position and then add it with the others using recursion

the point of this exercise is to multiply a digit of a number with its current position and then add it with the others. Example: 1234 = 1x4 + 2x3 + 3x2 + 4x1 .I did this code successfully using 2 parameters and now i'm trying to do it with 1. My idea was to use - return num + mult(a/10) * (a%10) and get the answer, , because from return num + mult(a/10) i get the values 1,2,3,4- (1 is for mult(1), 2 for mult(12), etc.) for num, but i noticed that this is only correct for mult(1) and then the recursion gets wrong values for mult(12), mult(123), mult(1234). My idea is to independently multiply the values from 'num' with a%10 . Sorry if i can't explain myself that well, but i'm still really new to programming.
#include <iostream>
using namespace std;
int mult(int a){
int num = 1;
if (a==0){
return 1;
}
return ((num + mult(a/10)) * (a%10));
}
int main()
{
int a = 1234;
cout << mult(a);
return 0;
}
I find this easier and more logically to do, Hope this helps lad.
int k=1;
int a=1234;
int sum=0;
while(a>0){
sum=sum+k*(a%10);
a=a/10;
k++;
}
If the goal is to do it with recursion and only one argument, you may achieve it with two functions. This is not optimal in terms of number of operations performed, though. Also, it's more of a math exercise than a programming one:
#include <iostream>
using namespace std;
int mult1(int a) {
if(a == 0) return 0;
return a % 10 + mult1(a / 10);
}
int mult(int a) {
if(a == 0) return 0;
return mult1(a) + mult(a / 10);
}
int main() {
int a = 1234;
cout << mult(a) << '\n';
return 0;
}

Counting number of digits in an integer through recursion

My code is following:
/counting number of digits in an integer
#include <iostream>
using namespace std;
int countNum(int n,int d){
if(n==0)
return d;
else
return (n/10,d++);
}
int main(){
int n;
int d;
cout<<"Enter number"<<endl;
cin>>n;
int x=countNum();
cout<<x;
return 0;
}
i cannot figure out the error,it says that
: too few arguments to function `int countNum(int, int)'
what is issue?
Because you declared the function to take two arguments:
int countNum(int n,int d){
and you are passing none in:
int x = countNum();
You probably meant to call it like this, instead:
int x = countNum(n, d);
Also this:
return (n/10,d++);
should probably be this:
return countNum(n/10,d++);
Also you are not initializing your n and d variables:
int n;
int d;
Finally you don't need the d argument at all. Here's a better version:
int countNum(int n){
return (n >= 10)
? 1 + countNum(n/10)
: 1;
}
and here's the working example.
int x=countNum(); the caller function should pass actual arguments to calling function. You have defined function countNum(int, int) which means it will receive two ints as arguments from the calling function, so the caller should pass them which are missing in your case. Thats the reason of error too few arguments.
Your code here:
int x=countNum();
countNum needs to be called with two integers. eg
int x=countNum(n, d);
Because you haven't passed parameters to the countNum function. Use it like int x=countNum(n,d);
Assuming this is not for an assignment, there are better ways to do this (just a couple of examples):
Convert to string
unsigned int count_digits(unsigned int n)
{
std::string sValue = std::to_string(n);
return sValue.length();
}
Loop
unsigned int count_digits(unsigned int n)
{
unsigned int cnt = 1;
if (n > 0)
{
for (n = n/10; n > 0; n /= 10, ++cnt);
}
return cnt;
}
Tail End Recursion
unsigned int count_digits(unsigned int n, unsigned int cnt = 1)
{
if (n < 10)
return cnt;
else
return count_digits(n / 10, cnt + 1);
}
Note: With tail-end recursion optimizations turned on, your compiler will transform this into a loop for you - preventing the unnecessary flooding of the call stack.
Change it to:
int x=countNum(n,0);
You don't need to pass d in, you can just pass 0 as the seed.
Also change countNum to this:
int countNum(int n,int d){
if(n==0)
return d;
else
return coutNum(n/10,d+1); // NOTE: This is the recursive bit!
}
#include <iostream>
using namespace std;
int countNum(int n,int d){
if(n<10)
return d;
else
return countNum(n/10, d+1);
}
int main(){
int n;
cout<<"Enter number"<<endl;
cin>>n;
int x=countNum(n, 1);
cout<<x;
return 0;
}
Your function is written incorrectly. For example it is not clear why it has two parameters or where it calls recursively itself.
I would write it the following way
int countNum( int n )
{
return 1 + ( ( n /= 10 ) ? countNum( n ) : 0 );
}
Or even it would be better to define it as
constexpr int countNum( int n )
{
return 1 + ( ( n / 10 ) ? countNum( n/10 ) : 0 );
}

factorial of big numbers with strings in c++

I am doing a factorial program with strings because i need the factorial of Numbers greater than 250
I intent with:
string factorial(int n){
string fact="1";
for(int i=2; i<=n; i++){
b=atoi(fact)*n;
}
}
But the problem is that atoi not works. How can i convert my string in a integer.
And The most important Do I want to know if the program of this way will work with the factorial of 400 for example?
Not sure why you are trying to use string. Probably to save some space by not using integer vector? This is my solution by using integer vector to store factorial and print.Works well with 400 or any large number for that matter!
//Factorial of a big number
#include<iostream>
#include<vector>
using namespace std;
int main(){
int num;
cout<<"Enter the number :";
cin>>num;
vector<int> res;
res.push_back(1);
int carry=0;
for(int i=2;i<=num;i++){
for(int j=0;j<res.size();j++){
int tmp=res[j]*i;
res[j]=(tmp+carry)%10 ;
carry=(tmp+carry)/10;
}
while(carry!=0){
res.push_back(carry%10);
carry=carry/10;
}
}
for(int i=res.size()-1;i>=0;i--) cout<<res[i];
cout<<endl;
return 0;
}
Enter the number :400
Factorial of 400 :64034522846623895262347970319503005850702583026002959458684445942802397169186831436278478647463264676294350575035856810848298162883517435228961988646802997937341654150838162426461942352307046244325015114448670890662773914918117331955996440709549671345290477020322434911210797593280795101545372667251627877890009349763765710326350331533965349868386831339352024373788157786791506311858702618270169819740062983025308591298346162272304558339520759611505302236086810433297255194852674432232438669948422404232599805551610635942376961399231917134063858996537970147827206606320217379472010321356624613809077942304597360699567595836096158715129913822286578579549361617654480453222007825818400848436415591229454275384803558374518022675900061399560145595206127211192918105032491008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
There's a web site that will calculate factorials for you: http://www.nitrxgen.net/factorialcalc.php. It reports:
The resulting factorial of 250! is 493 digits long.
The result also contains 62 trailing zeroes (which constitutes to 12.58% of the whole number)
3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000
Many systems using C++ double only work up to 1E+308 or thereabouts; the value of 250! is too large to store in such numbers.
Consequently, you'll need to use some sort of multi-precision arithmetic library, either of your own devising using C++ string values, or using some other widely-used multi-precision library (GNU GMP for example).
The code below uses unsigned double long to calculate very large digits.
#include<iostream.h>
int main()
{
long k=1;
while(k!=0)
{
cout<<"\nLarge Factorial Calculator\n\n";
cout<<"Enter a number be calculated:";
cin>>k;
if (k<=33)
{
unsigned double long fact=1;
fact=1;
for(int b=k;b>=1;b--)
{
fact=fact*b;
}
cout<<"\nThe factorial of "<<k<<" is "<<fact<<"\n";
}
else
{
int numArr[10000];
int total,rem=0,count;
register int i;
//int i;
for(i=0;i<10000;i++)
numArr[i]=0;
numArr[10000]=1;
for(count=2;count<=k;count++)
{
while(i>0)
{
total=numArr[i]*count+rem;
rem=0;
if(total>9)
{
numArr[i]=total%10;
rem=total/10;
}
else
{
numArr[i]=total;
}
i--;
}
rem=0;
total=0;
i=10000;
}
cout<<"The factorial of "<<k<<" is \n\n";
for(i=0;i<10000;i++)
{
if(numArr[i]!=0 || count==1)
{
cout<<numArr[i];
count=1;
}
}
cout<<endl;
}
cout<<"\n\n";
}//while
return 0;
}
Output:
![Large Factorial Calculator
Enter a number be calculated:250
The factorial of 250 is
32328562609091077323208145520243684709948437176737806667479424271128237475551112
09488817915371028199450928507353189432926730931712808990822791030279071281921676
52724018926473321804118626100683292536513367893908956993571353017504051317876007
72479330654023390061648255522488194365725860573992226412548329822048491377217766
50641276858807153128978777672951913990844377478702589172973255150283241787320658
18848206247858265980884882554880000000000000000000000000000000000000000000000000
000000000000][1]
You can make atoi compile by adding c_str(), but it will be a long way to go till getting factorial. Currently you have no b around. And if you had, you still multiply int by int. So even if you eventually convert that to string before return, your range is still limited. Until you start to actually do multiplication with ASCII or use a bignum library there's no point to have string around.
Your factorial depends on conversion to int, which will overflow pretty fast, so you want be able to compute large factorials that way. To properly implement computation on big numbers you need to implement logic as for computation on paper, rules that you were tought in primary school, but treat long long ints as "atoms", not individual digits. And don't do it on strings, it would be painfully slow and full of nasty conversions
If you are going to solve factorial for numbers larger than around 12, you need a different approach than using atoi, since that just gives you a 32-bit integer, and no matter what you do, you are not going to get more than 2 billion (give or take) out of that. Even if you double the size of the number, you'll only get to about 20 or 21.
It's not that hard (relatively speaking) to write a string multiplication routine that takes a small(ish) number and multiplies each digit and ripples the results through to the the number (start from the back of the number, and fill it up).
Here's my obfuscated code - it is intentionally written such that you can't just take it and hand in as school homework, but it appears to work (matches the number in Jonathan Leffler's answer), and works up to (at least) 20000! [subject to enough memory].
std::string operator*(const std::string &s, int x)
{
int l = (int)s.length();
std::string r;
r.resize(l);
std::fill(r.begin(), r.end(), '0');
int b = 0;
int e = ~b;
const int c = 10;
for(int i = l+e; i != e;)
{
int d = (s[i]-0x30) * x, p = i + b;
while (d && p > e)
{
int t = r[p] - 0x30 + (d % c);
r[p] = (t % c) + 0x30;
d = t / c + d / c;
p--;
}
while (d)
{
r = static_cast<char>((d % c) +0x30)+r;
d /= c;
b++;
}
i--;
}
return r;
}
In C++, the largest integer type is 'long long', and it hold 64 bits of memory, so obviously you can't store 250! in an integer type. It is a clever idea to use strings, but what you are basically doing with your code is (I have never used the atoi() function, so I don't know if it even works with strings larger than 1 character, but it doesn't matter):
covert the string to integer (a string that if this code worked well, in one moment contains the value of 249!)
multiply the value of the string
So, after you are done multiplying, you don't even convert the integer back to string. And even if you did that, at one moment when you convert the string back to an integer, your program will crash, because the integer won't be able to hold the value of the string.
My suggestion is, to use some class for big integers. Unfortunately, there isn't one available in C++, so you'll have to code it by yourself or find one on the internet. But, don't worry, even if you code it by yourself, if you think a little, you'll see it's not that hard. You can even use your idea with the strings, which, even tough is not the best approach, for this problem, will still yield the results in the desired time not using too much memory.
This is a typical high precision problem.
You can use an array of unsigned long long instead of string.
like this:
struct node
{
unsigned long long digit[100000];
}
It should be faster than string.
But You still can use string unless you are urgent.
It may take you a few days to calculate 10000!.
I like use string because it is easy to write.
#include <bits/stdc++.h>
#pragma GCC optimize (2)
using namespace std;
const int MAXN = 90;
int n, m;
int a[MAXN];
string base[MAXN], f[MAXN][MAXN];
string sum, ans;
template <typename _T>
void Swap(_T &a, _T &b)
{
_T temp;
temp = a;
a = b;
b = temp;
}
string operator + (string s1, string s2)
{
string ret;
int digit, up = 0;
int len1 = s1.length(), len2 = s2.length();
if (len1 < len2) Swap(s1, s2), Swap(len1, len2);
while(len2 < len1) s2 = '0' + s2, len2++;
for (int i = len1 - 1; i >= 0; i--)
{
digit = s1[i] + s2[i] - '0' - '0' + up; up = 0;
if (digit >= 10) up = digit / 10, digit %= 10;
ret = char(digit + '0') + ret;
}
if (up) ret = char(up + '0') + ret;
return ret;
}
string operator * (string str, int p)
{
string ret = "0", f; int digit, mul;
int len = str.length();
for (int i = len - 1; i >= 0; i--)
{
f = "";
digit = str[i] - '0';
mul = p * digit;
while(mul)
{
digit = mul % 10 , mul /= 10;
f = char(digit + '0') + f;
}
for (int j = 1; j < len - i; j++) f = f + '0';
ret = ret + f;
}
return ret;
}
int main()
{
freopen("factorial.out", "w", stdout);
string ans = "1";
for (int i = 1; i <= 5000; i++)
{
ans = ans * i;
cout << i << "! = " << ans << endl;
}
return 0;
}
Actually, I know where the problem raised At the point where we multiply , there is the actual problem ,when numbers get multiplied and get bigger and bigger.
this code is tested and is giving the correct result.
#include <bits/stdc++.h>
using namespace std;
#define mod 72057594037927936 // 2^56 (17 digits)
// #define mod 18446744073709551616 // 2^64 (20 digits) Not supported
long long int prod_uint64(long long int x, long long int y)
{
return x * y % mod;
}
int main()
{
long long int n=14, s = 1;
while (n != 1)
{
s = prod_uint64(s , n) ;
n--;
}
}
Expexted output for 14! = 87178291200
The logic should be:
unsigned int factorial(int n)
{
unsigned int b=1;
for(int i=2; i<=n; i++){
b=b*n;
}
return b;
}
However b may get overflowed. So you may use a bigger integral type.
Or you can use float type which is inaccurate but can hold much bigger numbers.
But it seems none of the built-in types are big enough.