multiply number in strings c++ [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
what I'm looking for is using simple math on number in string
I'm trying to find the factorial of 100 and it's really big to put it in int or long long so I searched and found that string is the best Solution but
I can't multiply numbers in string or even put in int the multiply then put it back in string and I can't use libraries not from the std of c++ and one can help me

To solve this, you will have to write some code that multiplies a number with another number.
Here's a function that multiplies the content of a string by two:
void times_two(char *str)
{
int carry = 0;
for(int i = DIGITS-2; i >= 0; i--)
{
int t = str[i] - '0';
t *= 2;
t += carry;
str[i] = (t % 10) + '0';
carry = (t > 9);
}
}
It presumes that the string is DIGITS characters long and "adjusted" to the right of the string with zeros to fill it out.
Of course, if you try to multiply by "more than a single digit", you will have to loop over the length of the number you are multiplying by, and you also have to care about "carry" being more than one for anything over two. But the principle is the same.
[I'm intentionally not rewriting my function above to cope with those two scenarios, becuase the prupose of you doing the factorial of 100 isn't to find the answer, but to learn how to solve programming problems. If all you wanted to do is find the answer, you could just use a modern calculator!]

Here's the code I once wrote runs in O(n^2) time. There are better algorithms though like fast fourier transformatons(fft) which runs in O(nlog n) time.
The multiply functions accepts 2 strings(numbers) and returns their product.
#define itc(n) char(n+48)
#define cti(ch) (ch-48)
string itos(lld n)
{
ostringstream convert;
convert<<n;
return convert.str();
}
string add(string s1, string s2)
{
int len1=s1.length(), len2=s2.length();
if(len1<len2) //s1 should be of greater length than s2
return add(s2, s1);
string ans="";
int carry=0, i, s;
for(i=1;i<=len1;i++)
{
s = carry+cti(s1[len1-i]);
if(i<=len2)
s += cti(s2[len2-i]);
ans = itc(s%10)+ans; //finding the character to be added to the ans
carry = s/10; //finding the carry
}
if(carry!=0)
ans = itc(carry)+ans;
return ans;
}
string multiply(string s1, string s2)
{
int len1=s1.length(), len2=s2.length();
if(len1<len2)
return multiply(s2,s1);
int i,j,p, carry=0;
string result, net="", c;
for(i=len2-1;i>=0;i--)
{
carry=0;
result="";
c="";
for(j=len1-1;j>=0;j--)
{
p=cti(s1[j])*cti(s2[i]);
result = itc((p+carry)%10)+result;
carry=(p+carry)/10;
}
if(carry!=0)
{
c=itos(carry);
result=c+result;
}
for(j=i;j<len2-1;j++)
result+="0";
net=add(net,result);
}
return net;
}

Related

Get number of digits in an int without divided by 10 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Is there a way to get the number of digits without the division by 10?
For example i have this:
int main()
{
int dividend = 100;
int remainder=0;
int temp = 0;
while(dividend>=10)
{
dividend = dividend-10;
temp+=1;
}
printf("Quotient: %d\n",temp);
printf("Reminder: %d\n",dividend);
}
And now I will add to calculate the number of digits of the variable dividend.
You have to know the maximum range of integer to make this function usefull.
no function call, no division ...
int nbDigitInteger(int number)
{
if (-10 < number && number < 10) return (1);
if (-100 < number && number < 100) return (2);
if (-1000 < number && number < 1000) return (3);
if (-10000 < number && number < 10000) return (4);
if (-100000 < number && number < 100000) return (5);
...
}
Sometime, the simplier is the best.
If you are allowed to use logarithms then
int i = 123456;
int digitsCount = ceil(log10(abs(i)+1.0));
cout << digitsCount;
6
Your question is too broad, and the code is also unrelated.
Since you attempted to post the code, I'll provide the guidelines for the problem you asked for. Write the code yourself.
Take the absolute integer value. (abs())
Print it to a (large enough) buffer. (sprintf()/ snprintf()).
Use strlen() to get the length of the buffer (as string).
An alternative to the very elegant solution o #Yola is this.
intPow10 is returning 10 to the power exponent. I did not use pow from math.h, since it is numerically expensive and as #Tom's pointed out it can lead to invalid results.
#include <stdio.h>
#include<math.h>
int intPow10(int exponent){
int retval=1;
while (exponent){
retval *=10;
exponent --;
}
return retval;
}
int numDigits(const int i) {
int digits = 1;
while (intPow10(digits) <= fabs(i)) {
digits++;
}
printf("%i has %i digits.\n", i,digits);
return digits;
}
int main() {
numDigits(1);
numDigits(-1);
numDigits(10);
numDigits(13);
numDigits(-112312);
}
Is this code golf or what?
int b = 1000;
char a[10] = itoa(b);
printf("%d\n", strlen(a)); // 4
This simply turns b into a string, which is a. Then, prints the length. What would we do without atoi() and itoa()? Our own functions!

Printing the digits of an integer in correct order using recursion [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
How to print the digits of an integer of unknown length, in its correct order, using a single recursive function??
int digit(int n)
{
if (n==0)
{
}
else
{
cout << n%10 << endl;
return digit(n/10);
}
}
//the above function prints it in reverse
This would work;
[EDIT: The code works for inputs i.e. +ve, 0, -ve integers; it prints the digits only, not a -ve sign]
void digit(int n) //no need to return a value
{
if (n < 0)
n = -1*n;
if (n/10 > 0) //no need have else blocks
{
//for the correct order, make the recursive call first
digit(n/10);
}
//print when you reach the most significant digit
cout << n%10 << endl;
}
You have to think about, what step to take in a single function call and what to delegate to the next function call. Printing one digit seems to be a good candidate. Taking the least significant (right most) digit is quit easy: it's the remainder of dividing the integer by 10.
As you want to output the least significant digit at last, you have to delegate to your function first:
digit( n / 10 );
std::cout << n % 10;

Converting integer into array of digits [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to convert two integers into two arrays of digits, so for example 544 would become arr[0] = 5, arr[1] = 4, arr[2] = 4.
I have found some algorithms doing this, but they create new array, and return this. I would have to allocate this memory for two arrays, so I wanna pass two integers by reference and do this on them directly.
I guess I can do this, because these integers are in fact template types, so they should be changeable. That's why I added C++ tag here.
Just using something like this:
int n = 544; // your number (this value will Change so you might want a copy)
int i = 0; // the array index
char a[256]; // the array
while (n) { // loop till there's nothing left
a[i++] = n % 10; // assign the last digit
n /= 10; // "right shift" the number
}
Note that this will result in returning the numbers in reverse order. This can easily be changed by modifying the initial value of i as well as the increment/decrement based on how you'd like to determine to length of the value.
(Brett Hale) I hope the poster doesn't mind, but I thought I'd add a code snippet I use for this case, since it's not easy to correctly determine the number of decimal digits prior to conversion:
{
char *df = a, *dr = a + i - 1;
int j = i >> 1;
while (j--)
{
char di = *df, dj = *dr;
*df++ = dj, *dr-- = di; /* (exchange) */
}
}
A simple solution is:
int i = 12312278;
std::vector<int> digits;
while (i)
{
digits.push_back(i % 10);
i /= 10;
}
std::reverse(digits.begin(), digits.end());
or, string based ( i >= 0 )
for (auto x : to_string(i))
digits.push_back(x-'0');
Call the integer a.
To get the units digit of a, a % 10
To shift a down so the tens is the units digit, a / 10
To know when you're done, a == 0
To know how large your array needs to be in the first place, min(ceil(log(a+1, 10)), 1) (to convince yourself this works, try the logarithm part of it in a calculator. if you don't have multiple argument log, use the identity log(x,y) == log(x)/log(y))
You can do something like this if you are using C++:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a=544;
stringstream str;
str << a;
string arr;
str>>arr;
for(int i=0; i<arr.length(); i++)
{
cout << arr[i];
}
system("pause");
return 0;
}

How to convert a base-26 string to an integer? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have a string "D", that I want to convert into the integer 4.
(Additional information from OP)
D should convert into a decimal value . I want it to be "4".
for D = "4" ; E = "5"; and so on...
It may have the combination . If AA comes ,the value should be 27 and ll increase consequetively.
It looks like this is what you want (based on your question and comments):
unsigned long long convert(string str)
{
unsigned long long result = 0;
for (int i = 0;i<str.length();i++)
result+= (str[i] - 'A' + 1) + i*26;
return result;
}
Now for "D" it will give 4, for "AA" it will give 1+26 = 27 and so on...
A one-character string isn't so hard:
const int fromBase26 = ('D' - 'A') + 1;
This will set fromBase26 to 4.
For n-digit base parsing the algorithm is something like:
set output to 0
while input digits to convert:
output *= base
output += least significant input digit
remove least significant input digit from input
Note that this reads digits from the right of the input.
char* str = "ABC";
int i, len, num, pos;
len = strlen(str);
num = 0;
pos = 1;
for (i = 0; i < len; i++) {
num += pos * ((str[i] - 'A') + 1);
pos *= 26;
}
num will contain the result.

How I do fibonaci sequence under 1000? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
#include <iostream>
using namespace std;
void main()
{
int i = 0;
while (i < 1000)
{
int TEMP = i * 2;
cout << i << endl;
TEMP = i;
i = i +1;
// ???
}
return;
}
I'm so confused?? :(
The Fibonacci sequence F is F(n) = F(n - 1) + F(n - 2), F(0) = 0, F(1) = 1.
Here's some psuedo-code:
Start Counter1 at 0
Start Counter2 at 1.
For i = 0 to 1000
New value = Counter1 + Counter2
Print new value
Counter2 = Counter1
Counter1 = New Value
End For
This doesn't print out 0 or 1; it starts at F(2). You can easily fix this by just printing out 0 and 1 first. Also, this code prints the first 1000 numbers. If you change this to: While Counter1 < 1000, you'll stop when you reach or pass 1000.
It's up to you to implement it, and make sure you understand how it works.
First you should check that you understand the definition of the Fibonacci numbers.
By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
You need two variables to remember the state, not just one as you were trying to do. And you don't multiply by two, you just add the two variables.
#include <iostream>
using namespace std;
int main()
{
int i = 0;
int j = 1;
while (i < 1000)
{
/* Print a number. */
cout << i << endl;
/* Set j to the sum of i and j, and i to the old value of j. */
int TEMP = j;
j += i;
i = TEMP;
}
return 0;
}
If you would like just a hint, Google "recursion".
If you would like the answer, Google "recursion fibonacci C++", but PLEASE try to work it out with the hint above :) It's worth it.