How to show large integer numbers on C++ - c++

I am developing a single code that calculates Fatorial Number on C++.
The code
// Exemple: 5! = 5 x 4 x 3 x 2 x 1 = 120
#include <iostream>
using namespace std;
int main() {
int number, total;
cout << "Calculate fatorial number" << endl;
cout << "-------------------" << endl << endl;
cout << "Type a number... ";
cin >> number;
total = 1;
for (int i = number; i > 0; i-- ){
if (i == number){
total = i * total;
cout << number << "! = " << i << " x ";
} else if (i > 1) {
total = i * total;
cout << i << " x ";
} else {
total = i * total;
cout << i << " = ";
}
}
cout << total;
return 0;
}
The problem
When I give it numbers, do not return as expected.
What I want
I Want to know how bypass the bigger number problems so I can calculate at least 100!
Codes Output
number = 10; total = 3628800
number = 20 ; total = -2102132736
Compiler used
OnlineGDB

You need to either use an existing library that deals with large numbers, or implement your own. There's many options, gnu multi-precision, boost, etc...
If you choose to implement your own, you'll store digits in something like:
A string "90120304153543643626424262"
A std::vector<int> of digits (base 10)
{9,0,1,2,0,....}
A std::vector<int> of digits (large base, for efficiency. 2^16 works well)
{42567, 29183, 10987, ...}
Then, you'd need to roll your own multiplication, addition, assignment.

I guess you are searching for bignum arithmetic. You probably need to select some arbitrary-precision arithmetic library like GNU MP and use it.

hello the way i solve for large numbers is by doing this
#include <iostream>
using namespace std;
typedef unsigned long long int bigint; //big int
int main() {
bigint total = 9494949494949497989;
cout<<total<<endl;
return 0;
}
so i make a custom data type called bigint and then instead of doing int total i do bigint total thus i am able to store large int values

Related

Including Missing Data in a C++ Array

I am new to C++.
Below is code that lets a user enter five elements into an array, then sums those values, and obtains the mean and a predicted future value.
The code works fine if the user enters five elements, but how do I handle the situation in which one or more values are missing?
I have written code further below that seems to solve this problem, by defining a missing value to be a negative number. That code also seems to work fine. But, is there a better, accepted way of handling missing values in a C++ array?
If I try to run the first code in Microsoft Visual Studio 2019, I do not even know what to enter for a missing value. If I do not enter anything, and just press the Enter key, nothing happens.
Here is the original code that works with five elements. This code is slightly modified from code written by Saldina Nurak:
#include <iostream>
using namespace std;
int nmonths = 6;
int totalmonths = 24;
int main()
{
// {100, 220, 300, 0, 200, 250}
// This line works in the command window
// float monthArray[nmonths];
// for Microsoft Visual Studio 2019
float monthArray[6];
float total = 0;
for(int i = 0; i <= (nmonths-1); i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> monthArray[i];
total += monthArray[i];
}
float average = total / nmonths;
float inTwoYears = average * totalmonths;
cout << "total = " << total << endl;
cout << "average = " << average << endl;
cout << "inTwoYears = " << inTwoYears << endl;
}
Enter Amount 1: 100
Enter Amount 2: 220
Enter Amount 3: 300
Enter Amount 4: 0
Enter Amount 5: 200
Enter Amount 6: 250
total = 1070
average = 178.333
inTwoYears = 4280
Here is the modified code I wrote that seems to handle missing values, by defining them to be negative numbers:
#include <iostream>
using namespace std;
int nmonths = 6;
int totalmonths = 24;
int emptycounter = 0;
int main()
{
// This works from the command window
// float monthArray[nmonths]; // {100, 220, 300, 0, -99, 250};
// for Microsoft Visual Studio I have to use
float monthArray[6];
float total = 0;
for(int i = 0; i <= (nmonths-1); i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> monthArray[i];
if (monthArray[i] >= 0) emptycounter++;
else (emptycounter = emptycounter);
if (monthArray[i] >= 0) total += monthArray[i];
else total = total;
}
float average = total / emptycounter;
float inTwoYears = average * (totalmonths - (nmonths - emptycounter));
cout << "total = " << total << endl;
cout << "average = " << average << endl;
cout << "inTwoYears = " << inTwoYears << endl;
}
C:\Users\mark_>cd C:\Users\mark_\myCppprograms
C:\Users\mark_\myCppprograms>c++ MissingDataInArray2.cpp -o MissingDataInArray2.exe -std=gnu++11
C:\Users\mark_\myCppprograms>MissingDataInArray2
Enter Amount 1: 100
Enter Amount 2: 220
Enter Amount 3: 300
Enter Amount 4: 0
Enter Amount 5: -99
Enter Amount 6: 250
total = 870
average = 174
inTwoYears = 4002
What is the standard approach for dealing with missing values in C++ and how does a user enter a missing value from the keyboard?
You would have to define what is supposed to be a missing value if you are trying to read as a number. You could maybe read the line and try to parse it to a int and if unable to parse then it would be your missing value?
Also, you are not using C++ arrays, you are using C arrays.
C++ has an array container but vector gives you much more flexibility.
You could do something like this:
vector<int> monthArray;
int value;
for(int i = 0; i < nmonths; i++) // See the change done in the test
{
cin >> value;
if(value > 0)
monthArray.push_back(value); // This would insert at the end and take care of resizing the container as needed.
}
monthArray.size(); // This returns how many elements you have in the container
Both your else clauses are assigning a variable to itself. You can erase both and put the 2 statements inside the same if:
if (monthArray[i] >= 0)
{
emptycounter++;
total += monthArray[i];
}
But if you use vector you won't need emptycounter. The size of the vector will contain the number of valid elements.
for(int i = 0; i < nmonths; i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> value;
if(value > 0)
{
monthArray.push_back(value);
total += value;
}
}
After all that... There is this question: Do you really need an array? You just seem to accumulate the valid values and never refer to the array after saving the elements on it.
P.S: to use vector you need to #include<vector>
What is the standard approach for dealing with missing values in C++ ?
std::optional is standard and serves the need.
How does a user enter a missing value from the keyboard?
There is no definition of operator>> for istream and std::optional<float> but you can write a function that behaves the way you want.
For example you could use std::getline to always read an entire line, then if the line is blank return an empty std::optional<float> and if not then parse the number and return a std::optional<float> that contains it.
Here is code that implements the answer from #vmp when missing observations are defined as NA (as in R and suggested by #Yksisarvinen in a comment) by using stoi. I have not yet figured out how to implement the answer from #Ben Voigt.
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int nmonths = 6 ;
int totalmonths = 24 ;
int main()
{
float total = 0;
vector<int> monthArray;
string value;
for(int i = 0; i < nmonths; i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> value;
if(value != "NA")
{
monthArray.push_back(stoi(value));
total += stoi(value);
}
}
float average = total / monthArray.size() ;
float inTwoYears = average * (totalmonths - (nmonths - monthArray.size())) ;
cout << "total = " << total << endl;
cout << "average = " << average << endl;
cout << "inTwoYears = " << inTwoYears << endl;
}
// C:\Users\mark_>cd C:\Users\mark_\myCppprograms
// C:\Users\mark_\myCppprograms>c++ vector2.cpp -o vector2.exe -std=gnu++11
// C:\Users\mark_\myCppprograms>vector2
// Enter Amount 1: 100
// Enter Amount 2: 220
// Enter Amount 3: 300
// Enter Amount 4: 0
// Enter Amount 5: NA
// Enter Amount 6: 250
// total = 870
// average = 174
// inTwoYears = 4002

Total number of odd/even numbers

Hello I'm trying to display only the amount of odd/even numbers for the digits entered. I've tried multiple methods but failed to find any solution. This is the problem and what I have so far.
Write a program that allows the user to enter 10 separate whole numbers. After accepting these 10 numbers from the user, the program should display output to the user informing them how many of the numbers entered were odd numbers and how many were even numbers.
#include <iostream>
using namespace std;
int main() {
char even, odd;
int number;
for(int i = 1;i<=10;i++) {
cout << "Enter Number " << i << ":" ;
i=i+0;
cin >> number ;
}
if (number%2==0){
number = even;
}
cout<< "You entered:\n";
cout << "Odd Numbers: " << odd << endl;
cout << "Even Numbers: " << even << endl;
return 0;
}
There are a few things in your code that do not look right.
for(int i = 1; i <= 10; i++)
{
cout << "Enter Number " << i << ":";
i = i + 0;
cin >> number;
}
What are you hoping to accomplish with the line i = i + 0? Your loop will work just fine without it.
char even, odd;
Technically, since char is a numeric type, you may keep track of the number of even and odd numbers encountered by keeping track of them. However, you aren't doing that.
The statement:
if (number%2==0){
number = even;
}
Is saying that if the input number is even, assign the current value of char even to number. However, this doesn't make sense, since you never stored a value in even earlier. Also, you're doing this outside the loop, so effectively only the last of the 10 values read into number would ever be counted in your calculations (if you had that done correctly).
What you should do:
int even = 0, odd = 0;
for(...)
{
// read input into "number"...
if(number % 2 == 0)
{
even++;
}
else
{
odd++;
}
}

C + + Can I use arrays here to shorten my code?

This is my first post on here so please don't kill me for my noobishness.
I recently made a program for fun to put in a ton of numbers and have it put out the mean, not very useful but I thought I would see if I could. I would love it if someone could explain to me how I could improve my code using arrays instead of lots of variables, but still achieve the same thing, maybe even more efficiently.
My code looks like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int q1;
int q2;
int q3;
int q4;
int q5;
int q6;
int q7;
int q8;
int q9;
int q10;
int q11;
int q12;
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
cin >> q1;
cin >> q2;
cin >> q3;
cin >> q4;
cin >> q5;
cin >> q6;
cin >> q7;
cin >> q8;
cin >> q9;
cin >> q10;
cin >> q11;
cin >> q12;
f = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12;
cout << f / a << '\n';
system("pause");
}
Any advice is very appreciated! This was made in Visual Studio just in case you needed to know.
Of course arrays can make your life easier!
Here's how you could have accomplished the same task as above, with arrays:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "You can only enter up to 12 numbers;
// Declare an array to hold 12 int's
int nums[12];
// i will count how many numbers have been entered
// sum will hold the total of all numbers
int i, sum = 0;
for(i = 0; i < 12; i++) {
cout << "Enter the next number: ";
cin >> nums[i];
sum += nums[i];
}
cout << "The mean is: " << (sum / totalNums) << '\n';
//Try to avoid using system!
system("pause");
}
But, why use an array?
There's no need to keep any of the numbers after you add them to the total, so why use an array?
You can accomplish the same task without an array and with only one variable for the numbers!
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "Enter the amount of numbers that will be entered: ";
cin >> totalNums;
// i will count how many numbers have been entered
// sum will hold the total of all numbers
// currentNum will hold the last number entered
int i, sum = 0, currentNum = 0;
for(i = 0; i < totalNums; i++) {
cout << "Enter the next number: ";
cin >> currentNum;
sum += currentNum;
}
cout << "The mean is: " << 1.0 * sum / totalNums << '\n';
//Try to avoid using system!
system("pause");
}
Arrays can be considered as series of variables each of which has ids.
integers between 0 and (number of elements) - 1 (both inclusive) are available ids.
Using that with loop, your code can be like this (sorry, I hate stdafx.h):
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int q[12];
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
for (int i = 0; i < 12; i++) {
cin >> q[i];
}
f = 0;
for (int i = 0; i < 12; i++) {
f += q[i];
}
cout << f / a << '\n';
system("pause");
}
You may use the numbers read in the future, but currently the numbers aren't used except for calculating the sum, so you can omit the array and do addition while reading. Also I deleted the variable t, which is unused and stopped using using namespace std;, which is not considered as good.
#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
int main() {
int q;
int f;
//Used for the total of all values
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
f = 0;
for (int i = 0; i < 12; i++) {
cin >> q;
f += q;
}
cout << f / a << '\n';
system("pause");
}
You marked this question as C++.
I recommend you do not use "using", and you should prefer vector over array.
Consider the following approach:
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
std::cout << "We will be finding a mean." << std::endl
<< "Enter numbers, and press ^d when complete.\n"
<< std::endl;
// Declare a vector to hold user entered int's
std::vector<int> intVec;
// the vector automatically keeps track of element count
do {
std::cout << "number: "; // prompt
int t = 0;
std::cin >> t; // use std::cin,
if(std::cin.eof()) break; // ^d generates eof()
intVec.push_back(t);
}while(1);
// there are several way to sum a vec,
// this works fine:
int sum = 0;
for (auto i : intVec) sum += i;
std::cout << "\n sum : " << sum
<< "\ncount : " << intVec.size()
<< "\n mean : " << (sum / intVec.size()) << std::endl;
return(0);
}
You can enter single item per line (neatness counts).
You can enter multiple integers separated by white space, but the above will give back a prompt for the integers already entered.
^d - generates an end of file input.
... press and hold 'Control' key and letter 'd' at same time
Note - does not handle error input - try entering a 'number' as 'num' string.
The accepted answer is definitely the most efficient way to transform your code using arrays, but one thing I would add is that in C++ dividing an integer by another integer can only ever result in an integer, and because you're trying to get the mean, it seems like you'd want to have the result in decimals, so you need to do one of two things:
Declare sum as a float for the purposes of diving it by totalNums to get the mean.
Cast one of the integers to either a float or a double so that the decimals won't get truncated, so the last cout statement would look like this:
cout << "The mean is: " << (double)sum/totalNums << endl;
In C++ the default for precision is 6, but you can change the number of decimal points that are displayed by adding #include <iomanip> and using the setprecision( ) function in the iomanip, which you can just add in the same output line:
cout << setprecision(x) << "The mean is: " << (double)sum/totalNums << endl;
where x is whatever precision you want.
If you want to try using dynamic memory
This is definitely not necessary for what you're doing, but it's interesting stuff and good practice!
One more thing is that if you want to be able to have the user enter integers indefinitely, you can dymanically allocate memory during runtime by declaring a array of pointers to integers (so it's an array of address locations instead of an array of integers) and some sentinal value so they can decide when to stop. That code would look like:
#include <iostream>
#include <iomanip>
using namespace std;
main( ) {
const int ARRAY_SIZE = 200;
const int SENTINAL = -999;
int totalNums = 0;
int sum = 0;
//declare an array of pointers to integers so
//the user can enter a large number of integers
//without using as much memory, because the memory
//allocated is an array of pointers, and the int
//aren't allocated until they are needed
int *arr[ARRAY_SIZE];
cout << "We will be finding a mean." << endl;
cout << "Enter integers (up to 200) or enter -999 to stop" << endl;
//add a conditional into the for loop so that if the
//user enters the sentinal value they will break out
//of the loop
for (int c = 0; c < ARRAY_SIZE; c++) {
//every time you iterate through the loop, create a new
//integer by using the new keyword using totalNums as
//the index
arr[totalNums] = new int;
cout << "Enter integer: ";
//input into the array of pointers by dereferencing it
//(so it refers to what the pointer is pointer to instead
//of the pointer)
cin >> *arr[totalNums];
if (*arr[totalNums] == SENTINAL)
break;
else {
sum += *arr[totalNums];
totalNums++;
}
}
cout << setprecision(3) << "The mean is: " << (float)sum / totalNums << endl;
}

logic help for smallest/largest value

I went thru so many version of the algorithm to sort smallest and largest that my brain is fried. The book up to this point and searching online haven't helped at all.
I'm having difficulties at saving the last.
I used 3 in, 10 cm and 5 cm as test cases. Entering 3 in first, becomes the largest, entering 5 cm second becomes smallest and then 10 cm becomes smallest again. Tried different version for over 2 hours, even re-wrote that entire section. In the book Programming Principles and Practices using C++, its in the review section, before that I cant find anything to help me out.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main()
{
vector<double>all_meters;
double smallest= 0,print_smallest, largest = 0,print_largest, num = 0;
string unit, s_input, num_s_input, small_unit, large_unit;
while(cin.good()){
cout << "\n\t\t\t\tEnter '|' to exit.\n\n";
cout << "\t\tNumber to compare followed by white space and unit:";
cin >> num_s_input;
if(num_s_input.compare("|") == 0 || (s_input.compare("|") == 0)){
double sum = 0;
for (double x : all_meters) sum+=x;
cout << "Sum: " << setprecision(4) << sum << "m\n";
cout << "Smallest number: " << print_smallest << small_unit << endl
<< "Largest number: " << print_largest << large_unit << endl
<< "Total number of values: " << all_meters.size() << endl
<< "All the entered numbers converted to meters are: \n";
for (double i = 0; i<all_meters.size(); ++i){
cout << all_meters[i] << setprecision(2) <<"m ";
}
cout << "\nAlright now, goodbye then !\n" << endl;
break;
}
else{
cin >> s_input;
num = strtod(num_s_input.c_str(), NULL);
unit = s_input;
double meter = 0;
if(unit=="cm"){
meter = num / 100;}
else if(unit=="in"){
meter = num / 39.370;}
else if(unit=="ft"){
meter = num / 3.2808;}
else if(unit=="m"){
meter = num;}
else {
cout << "\n\tYou entered wrong unit!\t\n";}
if(largest==0){
largest = meter;
print_largest = num;
large_unit = unit;
cout << num << unit << " largest so far.\n";
}
else if(smallest==0&&meter<largest){
smallest = meter;
print_smallest = num;
small_unit = unit;
cout << num << unit << " smallest so far.\n";
}
else if(largest<meter){
largest = meter;
print_largest = num;
large_unit = unit;
cout << num << unit << " largest so far.\n";
}
else if(smallest>meter){
smallest = meter;
print_smallest = num;
small_unit = unit;
cout << num << unit << " smallest so far.\n";
}
all_meters.push_back(meter);
sort(all_meters.begin(),all_meters.end());
}
}
}
Managed to solve it without using limit, added the new changes to the code. Thanks for the help guys !
More than likely your problem comes from the fact that you are initializing smallest to 0. If you never enter anything smaller than 0 then smallest will never change.
When finding the minimum and maximum values you want to set the the initial value to the largest or smallest number respectively that it can hold. So in this case we would use
double smallest = std::numeric_limits<double>::max();
double largest = std::numeric_limits<double>::lowest()
double num = 0;
This was anything in your data set should be less than smallest and everything should be grater than largest.
This does require #include <limits>
You need to choose a standard unit of measure. The question suggests meters, so use that (you can use float or double for this, depending on what precision you need).
The problem is then simple, create some variables for the sum, smallest seen, and largest seen, the for each new input, convert to the standard format, and update the variables.
The solution (to get you started, not working code) might look something like this:
// You can represent the different types of units as integers
float convertToMeters(float unconvertedValue, int unit) {
// Convert unconvertedValue based on unit
}
float smallest = std::numeric_limits<float>::max();
float largest = std::numeric_limits<float>::lowest();
float sum = 0.0f;
// Update for each new input
while (new_input) {
float convertedValue = convertToMeters(new_value, unit);
// Update total
sum += convertedValue;
// Update smallest and largest
if (convertedValue > largest) largest = convertedValue;
else if (convertedValue < smallest) smallest = convertedValue;
}
As Nathan mentioned, #include <limits> for the limits.

my code crashes when introducing giant numbers

i have the next code which asks the user to introduce a number larger than 100000000, and then it asks for a digit that the code must search in the number, finally the code shows how many times the digit appears on the number, it seems to be easy but i have a restriction:
the data type cannot be a string or a char, thats why i am using an int, but when i introduce a real big number like 100100010000100 the code just doesn´t work properly, how could i solve this, any ideas???if someone could help me out with this i would appreciate it a lot
#include <iostream>
using namespace std;
int searchDigit(long int num,int digit);
int main()
{
long int num;
int digit,x;
cout << "Give me the number: " << endl;
cin >> num;
cout << "Digit " << endl;
cin >> digito;
x = searchDigit(num,digit);
cout << "\nThe digit " << digit << " appears " << x << " times" << endl;
return 0;
}
int searchDigit(long int num,int digit)
{
int r,c,p = 0;
for(c = num;c != 0;c = c/10)
{
r = c % 10;
if(r == digit)
p++;
}
return p;
}
Notice that in searchDigit you have c = num in the for-loop. If long int is larger than int - which is true on many platforms - you will lose the high bits of num.
If you enabled more compiler warnings, this would probably be picked up. It's hard to be more specific, since you haven't provided information about the platform, compiler, or the flags used.