Adding big numbers using pointers (c++) - c++

i need help, the code below does not work as it returns nothing when i run it. I'm trying to add big number so large that the numbers wonโ€™t be able to be represented in the standard C++ integer data structures
mission.cpp
void Big2Add(const char * num1, const char * num2, char * result)
{
string a = num1;
string b = num2;
int min = (a.length() < b.length() ? a.length():b.length());
int max = (a.length() < b.length() ? b.length():a.length());
int *n1 = new int[max];
int *n2 = new int[max];
for (unsigned int i=0; i < a.length(); i++)
{
n1[i] = a.at(a.length() - 1 -i) - 48;
}
cout << a << endl;
for (unsigned int i=0; i < b.length(); i++)
{
n2[i] = b.at(b.length()-1 -i) - 48;
}
cout << b << endl;
int carry = 0;
int* sum = new int[max];
int k=0;
for (k = 0; k < max; k++)
{
sum[k] = (n1[k] + n2[k] + carry) % 10;
if ( (n1[k] + n2[k] + carry) >= 10)
carry = 1;
else carry = 0;
}
sum[max] = carry;
for (int j= max; j >= 0; j--)
{
*result = sum[j];
}
}
main.cpp
char result[10];
const char * num1 = "10";
const char * num2 = "10";
Big2Add(num1, num2, result);
cout << "Part 3" << endl;
cout << "The addition of " << num1 << " and " << num2 << " is " << result << endl;
cout << endl;

First obvious bug:
int* sum = new int[max];
...
sum[max] = carry;
You need to allocate max+1 in order to use position max.
Second and third obvious bugs:
*result = sum[j];
You forgot to advance result and you forgot to add '0'
Fourth, you forgot to null terminate the string.
Try:
for (int j= max; j >= 0; j--)
{
*(result++) = sum[j] + '0';
}
*result = 0;

ok it works now tks but my main problem now is that is that there is a extra zero in front of my answer if let say i do 10 plus 10 it will give me 010 or 100 with 10 it will give me 0110 but if i plus 99 with 99 it will give 198 y?
void Big2Add(const char * num1, const char * num2, char * result)
{
string a = num1;
string b = num2;
int max = (a.length() < b.length() ? b.length():a.length());
int *n1 = new int[max];
int *n2 = new int[max];
unsigned int i;
for (i=0; i < a.length(); i++)
{
n1[i] = a.at(a.length() - 1 -i) - 48;
}
for (int j = i; j < max; ++j)
{
n1[j] = 0;
}
for (i=0; i < b.length(); i++)
{
n2[i] = b.at(b.length()-1 -i) - 48;
}
for (int j = i; j < max; ++j)
{
n2[j] = 0;
}
int carry = 0;
int* sum = new int[max];
int k=0;
for (k = 0; k < max; k++)
{
sum[k] = (n1[k] + n2[k] + carry) % 10;
if ( (n1[k] + n2[k] + carry) >= 10)
carry = 1;
else carry = 0;
}
sum[max] = carry;
for (int j= max ; j >= 0; j--)
{
if(sum[0] == 0)
{
}
*(result++) = sum[j] + '0';
}
*result = 0;
}

Related

How to display this pyramid of numbers?

I have this task:
A user inputs a number N and you have to output this pyramid:
0
101
21012
.......
N.21012.N
For N=5 it will be :
0
101
21012
3210123
432101234
54321012345
I managed to only get it working for N<10 with this code:
int n;
cin >> n;
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < n - i; j++)
cout << " ";
int dir = -1;
for (int k = i; k <= i; k += dir) {
cout << k;
if (k == 0)
dir = 1;
}
cout << endl;
}
For N=10 it will look like this :
0
101
21012
3210123
432101234
54321012345
6543210123456
765432101234567
87654321012345678
9876543210123456789
10987654321012345678910
After the answers I settled on this :
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
int n, spaces;
string number;
cin >> n;
if (n < 10)
spaces = n;
else
{
spaces = 9;
int pwr = 0, k = n;
while (k > 9)
{
pwr++;
k /= 10;
}
for (int i = 1; i < pwr; i++)
{
spaces += pow(10, i) * 9 * (i + 1);
}
spaces += (n - pow(10, pwr) + 1) * (pwr + 1);
}
// cout << spaces << endl;
for (int i = 0; i < n + 1; i++)
{
for (int j = i; j > -1; j--)
number += to_string(j);
int len = number.length() - 1;
for (int j = 0; j < spaces - len; j++)
cout << " ";
for (int j = 1; j <= i; j++)
number += to_string(j);
cout << number << endl;
number.clear();
}
cout << endl;
return 0;
}
int padding(int n) {
constexpr auto singleDigitNumbersCount = 9;
constexpr auto doubleDigitNumbersCount = 90; // from 10 to 99
if (n < 10) return n;
if (n < 100) return 2*n - singleDigitNumbersCount;
return 3*n - doubleDigitNumbersCount - 2*singleDigitNumbersCount;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n + 1; i++) {
std::cout << std::string(padding(n) - padding(i), ' ');
for (int k = i; k >= 0; k--) {
cout << k;
}
for (int k = 1; k <= i; k++) {
cout << k;
}
cout << '\n';
}
return 0;
}
https://godbolt.org/z/EEaeWEvf4
I made this a bit ago Compiler Explorer
Not sure if that'd help ๐Ÿค”
Here is the working code:
#include <string>
#include <iostream>
using namespace std;
#define MAX_SPACE 50
int main()
{
int n;
cin >> n;
string output = "";
for (int i = 0; i < n + 1; i++)
{
for (int k = i; k >= 0; k--) {
output += to_string(k);
}
for (int k = 1; k <= i; k++) {
output += to_string(k);
}
for (uint8_t i = 0, max = MAX_SPACE - output.length() / 2.00; i < max; i++) // Print max spaces minus the integer length divided by 2
{
cout << " ";
}
cout << output << endl; // Print number
output = "";
}
return 0;
}

C++ getting segfaults on an array I already assigned values to

I was trying to do a problem on HackerEarth, and I am getting Segmentation Faults for this for loop:
for (int index = 0; index < 18; index++){
cout << arr_list[arr_index][index];
}
Even though I assigned values to arr_list[arr_index][index] in the loop right before (so I'm guessing the values are somehow not being saved, but I don't know how the values aren't being saved).
When I remove this for loop, I don't get any segfaults, and the cout information prints what's expected (the numbers I've inputted, with each digit twice for each cout inside the loop).
#include <iostream>
#include <string>
using namespace std;
void step(int arr_list[1000000][18], int cs, int N){
/**
int freq[100000] = {0};
for (int i = 0; i < N; i++){
int cur_arr[18];
for (int index = 0; index < 18; index++){
cur_arr[index] = arr_list[i][index];
}
if (cs == 4){
freq[cur_arr[0]*100 + cur_arr[1] * 10 + cur_arr[2]] += 1;
} else{
freq[cur_arr[18 - cs*5] * 10000 + cur_arr[18 - cs*5 + 1] * 1000 + cur_arr[18 - cs*5 + 2]*100 + cur_arr[18 - cs*5 + 3] * 10 + cur_arr[18 - cs*5 + 4]] += 1;
}
}
for (int i = 1; i < 100000; i++){
freq[i] += freq[i-1];
}
int new_arr_list[1000000][18];
for (int i = N-1; i >= 0; i--){
int pos;
int cur_arr[18];
for (int index = 0; index < 18; index++){
cur_arr[index] = arr_list[i][index];
}
if (cs == 4){
pos = cur_arr[0]*100 + cur_arr[1] * 10 + cur_arr[2];
} else{
pos = cur_arr[18 - cs*5] * 10000 + cur_arr[18 - cs*5 + 1] * 1000 + cur_arr[18 - cs*5 + 2]*100 + cur_arr[18 - cs*5 + 3] * 10 + cur_arr[18 - cs*5 + 4];
}
for (int index = 0; index < 18; index++){
new_arr_list[freq[pos] - 1][index] = arr_list[i][index];
}
freq[pos] --;
}
for (int i = 0; i < N; i++){
for (int index = 0; index < 18; index++){
arr_list[i][index] = new_arr_list[i][index];
}
}
**/
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T;
int arr_index = 0;
cin >> T;
int arr_list[1000000][18];
int max_len = 0;
for (int testcase = 0; testcase < T; testcase ++){
string a;
cin >> a;
int a_len = a.length();
if (a_len > max_len){
max_len = a_len;
}
int arr_entry[18];
for (int i = 0; i < a_len ; i++){
arr_entry[18 - a_len + i] = a[i] - 48;
}
for (int i = 0; i < 18 - a_len; i++){
arr_entry[i] = 0;
}
for (int index = 0; index < 18; index++){
arr_list[arr_index][index] = arr_entry[index];
cout << arr_entry[index];
cout << arr_list[arr_index][index];
}
for (int index = 0; index < 18; index++){
cout << arr_list[arr_index][index];
}
arr_index ++;
}
/**
for (int c = 1; c < 5; c++){
if (max_len > (c-1)*5){
step(arr_list, c, T);
for (int i = 0; i < T; i++){
int is_leading_zero = 1;
for (int j = 0; j < 18; j++){
if (is_leading_zero == 0){
cout << arr_list[i][j];
}else{
if (arr_list[i][j] != 0){
is_leading_zero = 0;
cout << arr_list[i][j];
}
}
}
cout << " ";
}
cout << "\n";
}
}
**/
}
I'm assuming this is a common error, and that I'm missing something simple that gives me segfaults for values I already assigned data to.
Does anyone know why this is happening?
You are allocating 72 MB on the stack:
int main()
{
[...]
int arr_list[1000000][18];
[...]
}
This is probably causing a stack overflow.
On the Microsoft Windows platform, the maximum stack size is, by default, 1 MB. On Linux, it is typically 8 MB.
When allocating such large amounts of memory, I recommend that you instead either use
dynamic memory allocation, or
a global variable, or
a static local variable.
This ensures that the array is not stored on the stack.

How to resolve the segmentation fault in this code?

I am trying to make an infix calculator for which I am currently trying to convert numbers entered in a character array to double.
here's my code:
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
char exp[500];
const int SIZE = 100;
char temp[SIZE];
char op;
int strLen = 0, k, l, num = 0, fnum = 0;
double number = 0;
cin.getline(exp, 500,'\n');
int i = 0, j = 0, fpoint=0;
cout << exp;
for (i = 0, j = 0; exp[j] != 0; i++)
{
if (i % 2 == 0)
{
for (int m = 0; exp[m] != ','; m++) //stopped working
temp[m] = exp[m];
cout << temp;
for (k = 0; k < SIZE && temp[k] != 0; k++)
{
strLen = k;
if (temp[k] == '.')
fpoint = k + 1;
}
cout << fpoint<<endl;
cout << "strLen" << strLen;
for (k = 0; k <= fpoint; k++)
{
num = num + ((temp[fpoint - k] - '0') * pow(10, k));
}
for (k = fpoint + 1, l = 0; k <= strLen; k++, l++)
{
fnum = fnum + ((temp[strLen - l] - '0') * pow(10, l));
}
number = num + (fnum / pow(10, strLen - fpoint + 1));
cout << number;
j = j + strLen + 1;
}
else
{
char op = temp[j];
cout << op;
}
}
system("pause");
return 0;
}
sample input
2.5*3
It stops working and gives segmentation fault as an error on the marked position.
This line for (int m = 0; exp[m] != ','; m++) //stopped working will always fail if there are no , characters since exp[m] != ',' will always be equal to true and so will reach beyond the end of the array of exp which triggers the "segmentation fault".

How do I get this random number generator out of an infinite loop?

I have an assignment for school where I need to create a lottery program. It is supposed to allow the user to input six numbers and then generate six random numbers for comparison. I got the inputs working, but I have encountered a problem where the random number generator (located in the while loop) is stuck in an infinite loop, and I have absolutely no idea what is causing it since I have never had an infinite loop in any previous programs. If someone could please look through the code and possibly establish what is wrong, I would greatly appreciate it.
#include<iostream>
#include<time.h>
using namespace std;
void randomizeSeed();
int randomRange(int min, int max);
int getInteger();
int main()
{
randomizeSeed();
const int minNumber = 1;
const int maxNumber = 49;
const int Size = 6;
int luckyNumbers[6] = {};
int randomNumber = randomRange(minNumber, maxNumber);
int winningNumbers[6] = {};
cout << "Enter six numbers between 1 and 49...\n";
{
for (int i = 0; i < Size; i++)
{
luckyNumbers[i] = getInteger();
}
for (int i = 0; i < Size; i++)
{
for (int i = 0; i < Size - 1; i++)
{
if (luckyNumbers[i] > luckyNumbers[i + 1])
{
int temp = luckyNumbers[i];
luckyNumbers[i] = luckyNumbers[i + 1];
luckyNumbers[i + 1] = temp;
}
}
}
cout << "Lucky Numbers: ";
for (int i = 0; i < Size; i++)
{
cout << luckyNumbers[i] << " ";
}
cout << "\n";
cout << "Press any button to see the Winning Numbers.\n";
system("pause");
bool exist = true;
while (exist == true)
{
int count = 0;
cout << "Winning Numbers: ";
for (int j = 0; j < 6; j++)
{
winningNumbers[j] = randomRange(1, 49);
cout << winningNumbers[j] << " ";
system("pause");
}
}
}
}
void randomizeSeed()
{
srand(time(NULL));
}
int randomRange(int min, int max)
{
int randomValue = rand() % (max + 1 - min) + min;
return randomValue;
}
int getInteger()
{
int value = 0;
while (!(cin >> value) || (value >= 50) || (value <= 0))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return value;
}
for (int i = 0; i < Size; i++)
for (int i = 0; i < Size - 1; i++)
if (luckyNumbers[i] > luckyNumbers[i + 1])
{
int temp = luckyNumbers[i];
luckyNumbers[i] = luckyNumbers[i + 1];
luckyNumbers[i + 1] = temp;
}
You have two loops and they both use i. You probably mean to use the second loop with another variable name, for example:
for (int i = 0; i < Size; i++)
{
for (int k = 0; k < Size - 1; k++)
{
if (luckyNumbers[i] > luckyNumbers[k + 1])
{
int temp = luckyNumbers[i];
luckyNumbers[i] = luckyNumbers[k + 1];
luckyNumbers[k + 1] = temp;
}
}
}
If you set your compiler warning level to 4 then compiler should warn you about these errors. Try to resolve all compiler warnings.

Solving an equation in an array with loop

An array of 'N' integers, it is necessary to calculate the next equation:
ัƒ = ั…1 * (ั…1 + ั…2) * (ั…1 + ั…2 + ั…3) * ... * (x1 + ... + xN)
I have two questions:
Is there a better way to find the solution y?
How to generate random number except of 0?
Code:
srand(time(NULL));
const int size = 10;
int arr[size];
int pro=1;
for (int i = 0; i < size; i++)
{
arr[i] = rand() % 10;
}
for (int i = 0; i < size; i++)
{
cout << arr[i] << ' ';
}
cout << endl;
for (int i = 0; i < size; i++)
{
int sum = 0;
for (int j = 0; j <= i; j++)
{
sum = arr[j];
}
pro *= sum;
}
cout << pro << endl;
How to generate random number except 0?
arr[i] = rand() % 9 + 1; // rando number in range 1 .. 9
Is there a better way to find the solution y?
long pro = 1;
long sum = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i]; // i==0: x1, i==1: x1+x2, i==3: x1+x2+x3, ....
pro *= sum;
}
This should be your code:
srand(time(NULL));
const int size = 10;
int arr[size];
for (int i = 0; i < size; i++)
arr[i] = rand() % 9 + 1;
for (int i = 0; i < size; i++)
cout << arr[i] << ' ';
cout << endl;
long pro = 1;
long sum = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i];
pro *= sum;
}
cout << pro << endl;