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.)
Related
Why does cin fail, when I enter a number like: 3999999999 but it works for smaller numbers like: 5 ?
#include <iostream>
int main()
{
int n;
std::cin >> n;
if (std::cin.fail())
std::cout << "Something sucks!";
else
std::cout << n;
return 0;
}
Try:
std::cout << std::numeric_limits<int>::max() << std::endl; // requires you to #include <limits>
int on your system is likely a 32-bit signed two's complement number, which means the max value it can represent is 2,147,483,647. Your number, 3,999,999,999, is larger than that, and can't be properly represented by int. cin fails, alerting you of the problem.
long may be a 64-bit integer on your system, and if it is, try that. You need a 64-bit integer to represet 3,999,999,999. Alternatively, you can use an unsigned int, which will be able to represent numbers as large as 4,294,967,295 (again, on the typical system). Of course, this means you can't represent negative numbers, so it's a trade-off.
That's probably because the big value is too big to fit into a variable of int type on your system. Try just assigning the big value to your variable and see what happens.
To fix it, change the type of the variable to a wider type, like long or long long.
The maximal number representable by an int depends on the number of bits it is represented. Usually, it's 32-bits, ie. the maximal number is 2147483647, which is smaller than the number you typed.
When the formatted input functions fail in some form, they set std::ios_base::failbit and leave the original value in the argument unchanged. There are different failures and overflows are considered one sort of failure. I recall a discussion about different errors being indicated in different ways but I din't recall the outcome. The best bet may be to make sure errno is cleared before calling any of the input functiins and checking errno for ERANGE to distinguish an overflow from a format error.
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;
}
I have the following piece of code for reading an input file and converting that input into an integer. It worked for some inputs but it isn't work anymore and that has been confusing me. (C++)
ifstream inputfile;
inputfile.open("inputfile.txt"); //openfile and read
string m; //fileforstringinput
getline(inputfile, m); //importing input information
long int s = atol(m.c_str()); //conversion to integer
inputfile.close(); //close file
cout << s;
When using this for small numbers it was fine. I tried the number from Project Euler problem 3 (600851475143)
and that failed to convert.
Does this exceed the size of long integers
Yes, it does. According to the <climits> header, the maximum value for long is 2147483647 (2^32/2 - 1).
You might try a 64-bit integer type (maximum 9223372036854775807), such as
long long
__int64
int64_t
The best choice will probably depend somewhat on your compiler and architecture. Some searching online might be required to find which type is correct for your setup.
Edit:
I originally suggested double as an alternative to long long, but Brian in the comments points out that it's probably a poor idea for prime factorization, which is inherently a whole-number operation. So strike that from the record and stick with something that models integers.
Does this exceed the size of long integers
Yes. A long integer is (usually) 4 bytes. It can only store values between -2,147,483,647 and 2,147,483,647.
Why does cin fail, when I enter a number like: 3999999999 but it works for smaller numbers like: 5 ?
#include <iostream>
int main()
{
int n;
std::cin >> n;
if (std::cin.fail())
std::cout << "Something sucks!";
else
std::cout << n;
return 0;
}
Try:
std::cout << std::numeric_limits<int>::max() << std::endl; // requires you to #include <limits>
int on your system is likely a 32-bit signed two's complement number, which means the max value it can represent is 2,147,483,647. Your number, 3,999,999,999, is larger than that, and can't be properly represented by int. cin fails, alerting you of the problem.
long may be a 64-bit integer on your system, and if it is, try that. You need a 64-bit integer to represet 3,999,999,999. Alternatively, you can use an unsigned int, which will be able to represent numbers as large as 4,294,967,295 (again, on the typical system). Of course, this means you can't represent negative numbers, so it's a trade-off.
That's probably because the big value is too big to fit into a variable of int type on your system. Try just assigning the big value to your variable and see what happens.
To fix it, change the type of the variable to a wider type, like long or long long.
The maximal number representable by an int depends on the number of bits it is represented. Usually, it's 32-bits, ie. the maximal number is 2147483647, which is smaller than the number you typed.
When the formatted input functions fail in some form, they set std::ios_base::failbit and leave the original value in the argument unchanged. There are different failures and overflows are considered one sort of failure. I recall a discussion about different errors being indicated in different ways but I din't recall the outcome. The best bet may be to make sure errno is cleared before calling any of the input functiins and checking errno for ERANGE to distinguish an overflow from a format error.
This is a very basic question.Please don't mind but I need to ask this. Adding two integers
int main()
{
cout<<"Enter a string: ";
int a,b,c;
cout<<"Enter a";
cin>>a;
cout<<"\nEnter b";
cin>>b;
cout<<a<<"\n"<<b<<"\n";
c= a + b;
cout <<"\n"<<c ;
return 0;
}
If I give a = 2147483648 then
b automatically takes a value of 4046724. Note that cin will not be prompted
and the result c is 7433860
If int is 2^32 and if the first bit is MSB then it becomes 2^31
c= 2^31+2^31
c=2^(31+31)
is this correct?
So how to implement c= a+b for a= 2147483648 and b= 2147483648 and should c be an integer or a double integer?
When you perform any sort of input operation, you must always include an error check! For the stream operator, this could look like this:
int n;
if (!(std::cin >> n)) { std::cerr << "Error!\n"; std::exit(-1); }
// ... rest of program
If you do this, you'll see that your initial extraction of a already fails, so whatever values are read afterwards are not well defined.
The reason the extraction fails is that the literal token "2147483648" does not represent a value of type int on your platform (it is too large), no different from, say, "1z" or "Hello".
The real danger in programming is to assume silently that an input operation succeeds when often it doesn't. Fail as early and as noisily as possible.
The int type is signed and therefor it's maximum value is 2^31-1 = 2147483648 - 1 = 2147483647
Even if you used unsigned integer it's maximum value is 2^32 -1 = a + b - 1 for the values of a and b you give.
For the arithmetics you are doing, you should better use "long long", which has maximum value of 2^63-1 and is signed or "unsigned long long" which has a maximum value of 2^64-1 but is unsigned.
c= 2^31+2^31
c=2^(31+31)
is this correct?
No, but you're right that the result takes more than 31 bits. In this case the result takes 32 bits (whereas 2^(31+31) would take 62 bits). You're confusing multiplication with addition: 2^31 * 2^31 = 2^(31+31).
Anyway, the basic problem you're asking about dealing with is called overflow. There are a few options. You can detect it and report it as an error, detect it and redo the calculation in such a way as to get the answer, or just use data types that allow you to do the calculation correctly no matter what the input types are.
Signed overflow in C and C++ is technically undefined behavior, so detection consists of figuring out what input values will cause it (because if you do the operation and then look at the result to see if overflow occurred, you may have already triggered undefined behavior and you can't count on anything). Here's a question that goes into some detail on the issue: Detecting signed overflow in C/C++
Alternatively, you can just perform the operation using a data type that won't overflow for any of the input values. For example, if the inputs are ints then the correct result for any pair of ints can be stored in a wider type such as (depending on your implementation) long or long long.
int a, b;
...
long c = (long)a + (long)b;
If int is 32 bits then it can hold any value in the range [-2^31, 2^31-1]. So the smallest value obtainable would be -2^31 + -2^31 which is -2^32. And the largest value obtainable is 2^31 - 1 + 2^31 - 1 which is 2^32 - 2. So you need a type that can hold these values and every value in between. A single extra bit would be sufficient to hold any possible result of addition (a 33-bit integer would hold any integer from [-2^32,2^32-1]).
Or, since double can probably represent every integer you need (a 64-bit IEEE 754 floating point data type can represent integers up to 53 bits exactly) you could do the addition using doubles as well (though adding doubles may be slower than adding longs).
If you have a library that offers arbitrary precision arithmetic you could use that as well.