C++ even and odd number checking with bigger values - c++

By using this little piece of code, i was finding even and odd numbers, but my curiosity grew when i enter number 8888888888(10 times) and it give me answer odd at the same time i again enter number 88888888(9 times) and it give me even number. Any one having idea about it.
Here is the code:
#include<iostream>
using namespace std;
int main(){
int a;
cin>>a;
if(a%2==0){
cout<<"even";
}else{
cout<<"odd";
}
}
I check this code on Dev C++ compiler. Thank you

Built-in numeric types have a limited range of values they can represent. 8888888888 is beyond the range of int on your platform. See std::numeric_limits.

Use the long keyword instead of int for large numbers: i.e. long a;.

As the others are saying, the standard built-in types are not big enough for what you are trying to do.
What i reccomend you to do is to build a class in which you can store big numbers. The easyest way to do this (if you don't really care about memory usage) is to store big numbers as seperate digits in an array.
It's even easyer if you only want to know if the number is even or odd:
if your input is a string you could just split of the last character and change it to an integer. This integer says everything about if the whole number is even or odd.
I hope this helps.
regards, Harm

In case of C++
The n1 and n2 are the string
if((n1[n1.size()-1] * n2[n2.size()-1]) % 2 == 0){
return 1;
}
else{
return 0;
}

Related

Why does this output have decimals? Also, it is far from correct answer

I am trying to calculate the sum of digits of 2^1000 in c++.
As you can see, the value of 2^1000 contains many zeroes and some digits, but even then the output of sum turns out to be in decimals.
My code is the following:
#include <bits/stdc++.h>
using namespace std;
main() {
cout<<fixed;
long double a=pow(2,1000),sum=0;
cout<<"2^1000 is"<<a<<"\n";
while(a) {
sum+=fmod(a,10);
a/=10;
}
cout<<sum;
}
I used fmod() since the % operator is not overloaded for long double, I had never used fmod() earlier but used it as mentioned here.
I don't really think fmod() is doing any mistake here, so any suggestion why the output of sum is in decimals? Futher, the correct answer should be 1366.
Here is the sample output:
Okay, so solved my problem by using this Bigint library!
You can't store 2^1000 in a single variable in C++. 2^1000 needs at least 1000 bits to be stored in binary, no variable of primitive type is long enough. So the first printed result is already wrong, remember that no power of 2 contains an ending 0 (2*2=4, 4*2=8, 8*2=16, 6*2=2). Then you cannot rely on the result of fmod.
2^1000=10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Different results for long long int in c and c++?

I am trying to solve a this problem-> Candy3
We are supposed to use long long to solve this problem. But when I'm using cin to take inputs that are larger than 10^19 (i know it is the limit of long long but the there is limit constraint specified and we are supposed to output the right answer) it is giving random outputs. Whereas, when I'm using scanf() it is printing the correct answer.
This is really weird. What is the difference b/w scanf and cin.
My code
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
int t,n;
cin>>t;
while(t--){
long long sum=0,sweet;
cin>>n;
for(int i=0; i<n; i++){
//cin>>sweet; printing yes no randomly
scanf("%lld", &sweet); // working correctly
sum = (sum + sweet)%n;
}
if(sum)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
return 0;
}
EDIT: This is a weird question and it is not specified in the question that what should be the size of input. Here is the input specification -
"The first line of the input file contains an integer T specifying the
number of test cases. Each test case is preceded by a blank line. Each
test case looks as follows: The first line contains N : the number of
children. Each of the next N lines contains the number of candies one
child brought."
As many people have noted, you're attempting to read integers which will overflow a long long.
The difference between scanf and cin.operator>>() with respect to integer overflow is that scanf does not (necessarily) test for integer overflow; if the number read is too big, the result is undefined behaviour. It's common that you'll just find an incorrect value in the corresponding argument, but there are no guarantees.
cin.operator>>(), on the other hand, does check for integer overflow, and if it finds integer overflow, it stores the largest possible integer of the indicated type and puts the cin stream into failure state. Once the stream is in failure state, it stays there until the state is cleared; furthermore, any subsequent use of cin.operator>>() will do nothing if the stream is in failure state.
Consequently, once you attempt to read an integer which is too large with cin.operator>>(), your code will find sweet to be the largest possible long long on every subsequent read.
So when using C++ formatted input, you need to always check for failure, and do something appropriate.
You say you're entering values bigger than 1019. That will probably overflow a long long.
Type long long is guaranteed to be at least 64 bits wide, and on every compiler I've seen it's exactly 64 bits wide. That means the maximum possible value of a long long is 263-1, or 9,223,372,036,854,775,807, which is approximately 9 * 1018.
If you enter a value of 1019, or 10,000,000,000,000,000, it will overflow. If cin << ... encounters a numeric overflow, it will fail; you haven't checked for that.
I don't believe that using scanf will solve this problem. scanf has undefined behavior if it reads a number outside the range of the specified type; storing a garbage value is a likely outcome. I can only guess that you're happen to be entering a smaller number with the scanf version of your program than with the cin >> ... version, and didn't notice that you were doing so.
You can use somewhat larger values (at the cost of not being able to store negative values) by using type unsigned long long, which has a minimum value of 0 and a maximum of at least 264-1, or 18,446,744,073,709,551,615, approximately 1.8 * 1019.
If you need even larger numbers, you might consider using floating-point, which gives you a much larger range at the expense of losing precision for large values.
Did you try to test small numbers such as 5, for example ? If it's working it's probably something in the number you enter which is probably out of the maximum that long long int can contain. Just try doing this on your system:
#include <iostream>
#include <stdio.h>
#include <limits>
using namespace std;
int main()
{
std::cout << std::numeric_limits<long long int>::max() << std::endl;
return 0;
}
and check if the value you entered is bigger than the one printed. If so, just declare a variable with enough space for the value, if the value printed is above the value you entered and there's STILL an error, comment on this post.
    I have also encountered this problem, and you can get an ac by scanf and get an error by cin because of the example is special. In fact, if there is an overflowing, using these two input methods will also be wrong.
    For long long type, for question I encountered at "A+B and C (64bit)", if we use the example data "9223372036854775808 -9223372036854775808 0" to A B C, we can get the error answer by the cin and get the correct answer by scanf;However, if we use the example data "9223372036854775808 -9223372036854775808 -1" to A B C, we can get the correct answer by cin and get the error answer by scanf.
    So we should use another method to solve the problem.(or the input data is in ( 2-63, 263 ), and the input data will be legal.)

Creating custom data type in c++

I'm writing a program to find the value of pi, and want it to show more than the standard 16 decimal places.
How do I create a variable that can hold more than 16 decimal places?
My current program is written below.
Using Dev-C++:
#include<iostream.h>
#include<conio.h>
#include<math.h>
int factorial(int a)
{
int b=1,c=1;
for(c; c<=a; c++)
{
b=b*c;
}
return b;
}
int main()
{
cout.precision(300);
long int n,a;
long double z=0,pi,num,den;
for(n=0; n<1000000; n++)
{ //begin for
num=(pow(factorial(2*n),3))*((42*n)+5);
den=(pow(factorial(n),6))*(pow(16,(3*n)+1));
z=z+(num/den);
pi=1/z;
if(n%1==0)
{
cout<<z<<endl; //test print statement
cin>>a;
cout<<pi;
cout<<endl;
}
}
getch();
return 0; //end for
}
If you don't want to use an existing high-precision arithmetic library, then here are a few pointers for writing your own. It will be a fair amount of work (and quite fiddly to debug), but quite a good learning exercise if you've got the time.
Store each number as an array of smaller "digits". For a very simple (but inefficient) implementation, these could literally be decimal digits, with values from 0 to 9 - this will then be very easy to print. For a more efficient implementation, I'd probably use 32-bit values for the "digits". You'll also need to decide how to represent negative numbers, whether the array should be fixed or variable size, and (for working with non-integers) whether the decimal point should be fixed or floating.
Implement basic arithmetic using the algorithms you learnt in primary school: addition with carry, subtraction with borrow, long multiplication and long division.
pow and factorial, needed for your algorithm can be implemented simply as repeated multiplication; other algorithms are available if this isn't fast enough (and for functions like sqrt and sin that can't be represented exactly with basic operations).
Sounds like you want a bignum library. Have a look at the GNU Multiple Precision Arithmetic Library for a widely-used open source alternative.
You can use one of the bigint libraries on the internet, for example: https://mattmccutchen.net/bigint/

error: invalid operands to binary % (have 'double' and 'double')

I have a program I am writing that lists 100,000 prime numbers. It works fine for 10 numbers, but after so many numbers they turn into negative values. I changed the ints to long ints and that did not change anything, then I changed them to doubles and I get the error listed in the title. What should my variable be? Keep in mind I am still new to programing. I also looked at some previous posts and did not see the answer.
int is_prime(double x,char array[]){
//doesnt use array but I put it in there
double j=2;//divider
for(j=2;j<=pow(x,0.5);j++){
if((x%j==0)){
return(0);
} //isnt prime
}
return(1);// because it is prime.
}
You can't use a double with the operator, you must have an int.
You should: #include <math.h> and then use the fmod function.
if(fmod(x,j)==0)
Full code:
#include <math.h>
int is_prime(double x,char array[]){
//doesnt use array but I put it in there
double j=2;//divider
for(j=2;j<=pow(x,0.5);j++){
if(fmod(x,j)==0){
return(0);
} //isnt prime
}
return(1);// because it is prime.
}
You have two options:
Stick with the % operator, then you're required to cast the inputs to ints
if(((int)x % (int)j) == 0)
Include math.h and then use fmod:
if(fmod(x, j) == 0)
Your immediate question can be solved with fmod, but for your purpose of high-value prime numbers, you may be better off looking at a big-integer class, like that at http://sourceforge.net/projects/cpp-bigint/ since what you really want is integer mathematics, and using floats might cause problems as things progress.

When I calculate a large factorial, why do I get a negative number?

So, simple procedure, calculate a factorial number. Code is as follows.
int calcFactorial(int num)
{
int total = 1;
if (num == 0)
{
return 0;
}
for (num; num > 0; num--)
{
total *= num;
}
return total;
}
Now, this works fine and dandy (There are certainly quicker and more elegant solutions, but this works for me) for most numbers. However when inputting larger numbers such as 250 it, to put it bluntly, craps out. Now, the first couple factorial "bits" for 250 are { 250, 62250, 15126750, 15438000, 3813186000 } for reference.
My code spits out { 250, 62250, 15126750, 15438000, -481781296 } which is obviously off. My first suspicion was perhaps that I had breached the limit of a 32 bit integer, but given that 2^32 is 4294967296 I don't think so. The only thing I can think of is perhaps that it breaches a signed 32-bit limit, but shouldn't it be able to think about this sort of thing? If being signed is the problem I can solve this by making the integer unsigned but this would only be a temporary solution, as the next iteration yields 938043756000 which is far above the 4294967296 limit.
So, is my problem the signed limit? If so, what can I do to calculate large numbers (Though I've a "LargeInteger" class I made a while ago that may be suited!) without coming across this problem again?
2^32 doesn't give you the limit for signed integers.
The signed integer limit is actually 2147483647 (if you're developing on Windows using the MS tools, other toolsuites/platforms would have their own limits that are probably similar).
You'll need a C++ large number library like this one.
In addition to the other comments, I'd like to point out two serious bugs in your code.
You have no guard against negative numbers.
The factorial of zero is one, not zero.
Yes, you hit the limit. An int in C++ is, by definition, signed. And, uh, no, C++ does not think, ever. If you tell it to do a thing, it will do it, even if it is obviously wrong.
Consider using a large number library. There are many of them around for C++.
If you don't specify signed or unsigned, the default is signed. You can modify this using a command line switch on your compiler.
Just remember, C (or C++) is a very low-level language and does precisely what you tell it to do. If you tell it to store this value in a signed int, that's what it will do. You as the programmer have to figure out when that's a problem. It's not the language's job.
My Windows calculator (Start-Run-Calc) tells me that
hex (3813186000) = E34899D0
hex (-481781296) = FFFFFFFFE34899D0
So yes, the cause is the signed limit. Since factorials can by definition only be positive, and can only be calculated for positive numbers, both the argument and the return value should be unsigned numbers anyway. (I know that everybody uses int i = 0 in for loops, so do I. But that left aside, we should use always unsigned variables if the value can not be negative, it's good practice IMO).
The general problem with factorials is, that they can easily generate very large numbers. You could use a float, thus sacrificing precision but avoiding the integer overflow problem.
Oh wait, according to what I wrote above, you should make that an unsigned float ;-)
If i remember well:
unsigned short int = max 65535
unsigned int = max 4294967295
unsigned long = max 4294967295
unsigned long long (Int64 )= max 18446744073709551615
Edited source:
Int/Long Max values
Modern Compiler Variable