my code crashes when introducing giant numbers - c++

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.

Related

C++ program to calculate the factorial of even numbers between 5 and 15

When I run the program for an even number less than 5, It prints out the error message but it also gives me the factorial. I don't want the factorial. Here's the code, how do I correct it?
#include <iostream>
using namespace std;
int main()
{
int number, factorial = 1;
cout << "Enter an even number between 5 & 15 to find it's factorial: ";
cin >> number;
if(number % 2 == 0) {
while(number < 5) {
cout << "Error! Enter an even number greater than five: ";
break;
}
while(number > 15) {
cout << "Error! Enter an even number less than fifteen: ";
break;
}
for(int a = 1; a <= number; a++) {
factorial = factorial * a;
}
cout << "factorial of " << number << " is " << factorial;
}
else {
cout << "Error!Enter an even number between 5 & 15 to find it's "
"factorial: ";
}
return 0;
}
This answer shows some corrections to be in your code and provide a working piece of code.
Corrections:
Not a very good idea to write everything in the main function. Try to follow SOLID principles where S stands for single responsibility. Which tells that functions must be small and do exactly one thing. And in your code, you have defined a very big function which does a lot of things.
Avoid nested loops. In your example, you have an if , inside which you have while, while and inside while you have for. This looks messy and is not readable.
Try to be clear in your expression of code, such that when a person reads they understand the flow of data.
Break is something that comes out of a while loop, but it does not mean it will exit the function. So in your example,
while(number<5){
std::cout<<"Error! Enter an even number greater than five: ";
break;
}
After it comes out of this loop, it will go to the next line which is another while loop and then goes on to calculate the function.
Try to use uniform initialization. Instead of int i = 0 use int i{0}. You can read more about uniform initialization on google.
Try not to use "using namespace std or anything else". Very bad practice.
Working piece of code:
bool check_value(int number){
int range = (number < 5 || number > 15) ? false : true;
int even = (number % 2 == 0) ? true : false;
if(range & even){
return true;
}
else{
std::cout << "Error! Please input even number between 5 & 15\n";
return false;
}}
int main(){
int number,factorial=1;
std::cout<<"Enter an even number between 5 & 15 to find it's factorial: \n";
std::cin >> number;
if(check_value(number)){
for (size_t a{1}; a <= number; a++){
factorial = factorial*a;
}
std::cout<<"factorial of " << number <<" is " << factorial << "\n";
}
return 0;
}
As Karl pointed out in the comments, the break statement will break out of exactly one loop, in this case a while loop, and the code outside of the loop will continue to execute.
Also, as Damien pointed out, you need to use a long long int to compute the factorial since the result can exceed the max size of the int datatype.
You could also reformulate your code to make it more readable, something like this:
#include <iostream>
/* Checks if number is valid and can throw error msg */
bool isValidNumber(int num) {
if(num % 2 != 0 || num < 5 || num > 15) {
std::cout << "Error! The number entered is not valid." << std::endl;
return false;
}
return true;
}
/* Calculates factorial and prints its value */
void calculateFactorial(int num) {
long long int factorial = 1;
for(int a = 1; a <= num; a++) {
factorial = factorial * a;
}
std::cout << "factorial of " << num << " is " << factorial << std::endl;
}
int main()
{
int number;
bool isValid;
do {
std::cout << "Enter an even number between 5 & 15 to find it's factorial: ";
std::cin >> number;
isValid = isValidNumber(number);
if(isValid) {
calculateFactorial(number);
}
} while(!isValid);
return 0;
}
Note: Using using namespace std; is considered bad practice because of the possibility of method collisions between a method or methods in the std namespace and methods of some other nanmespace you might create down the road.

How to show large integer numbers on 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

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++;
}
}

I keep getting a variable uninitialized error when calling a function that is asking for user input

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.

"Prime or not" program

I am stuck on this really simple program in C++, where I let the user know the number she/he have entered is prime or not, but, because of some reason, everything works fine during the first loop but things go fishy during the second. I would be more than happy if anyone could help ?
#include <iostream>
using namespace std;
int main(int argc, const char* argv[])
{
int number1 = 5;
int number;
int a = 0;
while (number1 == 5)
{
int b = 1;
cout << "Enter your number and we'll tell you if it's prime or not: ";
cin >> number;
while (a <= number)
{
a++;
if (number % a == 0)
b++;
}
if (b == 3)
cout << "Your number is prime" << endl;
else
cout << "Your number is not prime" << endl;
}
}
The are several problems with your program.
The first one is that the loop starting with statement
while (number1 == 5)
is infinite because number1 is not changed within the loop.
The second one is that you must always initialize variable a to zero within the loop. And it should be defined also within the loop because it is not used outside the loop. The same is valid for variable number.
Take into account that a number is prime if it is divisble by 1 and itself (except number 1). So I would initially set variable b to zero and compare it with 2. It is more clear than to compare it with 3.
The program can look the following way
#include <iostream>
int main()
{
while ( true )
{
std::cout << "Enter your number and we'll tell you if it's prime or not (0-exit): ";
unsigned int number = 0;
std::cin >> number;
if ( number == 0 ) break;
unsigned int n = 0;
unsigned int divisor = 0;
while ( divisor++ < number )
{
if ( number % divisor == 0 ) n++;
}
if ( n == 2 )
std::cout << "Your number is prime" << std::endl;
else
std::cout << "Your number is not prime" << std::endl;
}
}
You missed to reinit a to 0 before the inner while.
This makes it work. However, I suggest you take time to learn to code. It does not look educated.
Also your program won't exit. Not sure what your intention is, but you could omit the number1 variable and simply use while(1) (considering your code stands as is; probably you are at the beginning of your development though, so it depends).
#include <iostream>
using namespace std;
int main(int argc, const char* argv[])
{
int number1 = 5;
int number;
int a = 0;
while (number1 == 5)
{
int b = 1;
cout << "Enter your number and we'll tell you if it's prime or not: ";
cin >> number;
a = 0; <-- Reset to 0 would make it work
while (a <= number)
{
a++;
if (number % a == 0)
b++;
}
if (b == 3)
cout << "Your number is prime" << endl;
else
cout << "Your number is not prime" << endl;
}
}
P.S.: You are new to StackOverflow. So you likely take the answer and get away. Please consider accepting the answer. It's a respectful practice when it solved your issue.