long long division wrong - c++

I am working in a project and in a certain time I have this problem. I have two very large numbers and I want to divide them and get an integer/long long integer. This is what's happening:
Code
#include <iostream>
using namespace std;
int main(){
long long n,m;
cin >> n >> m;
cout << n/m << endl;
}
The inputs can be numbers until 100,000,000,000,000,000 so the division is performing wrong.
Output
#1 n: 76543210987654321 m: 7654321
#2 76543210987654321/7654321 = 1410312449
The right answer is 10,000,000,130 so I am wondering what is happening...

The correct result is neither 1410312449 nor 10000000130. It is equal to 10000000129
At least it is what the GCC shows at www.ideone.com. You can try it yourself.
#include <iostream>
int main()
{
long long n = 76543210987654321;
long long m = 7654321;
std::cout << n / m << std::endl;
return 0;
}
It seems that you place the result of the operation in an object of type int. Consider the following code
#include <iostream>
int main()
{
long long n = 76543210987654321;
long long m = 7654321;
int x;
x = n / m;
std::cout << n / m << std::endl;
std::cout << x << std::endl;
return 0;
}
The output is
10000000129
1410065537

It seems, that the result of division is truncated to 32-bit value (int).
Try to use explicit cast to long long via static_cast.
Also, it is interesting to know result of sizeof(long long) on your compiler.

Related

Why can't I set my long long variable to 1e18 + 10?

I have implemented a program in C++ and it showed a very strange bug.
First of all, if I assigned my variable a like this: long long a = 1e9 + 10 and then print the value of a, it ran correctly. But if I set a to 1e18 + 10 and then print the value of a, it showed that a equals 10^18 only. Can anyone help me with this? I tried a lot but I can't understand why. Thanks.
This is my code:
#include <iostream>
using namespace std;
int main() {
long long a = 1e9 + 10;
cout << a << endl;
a = 1e18 + 10;
cout << a << endl;
return 0;
}
1e18 is a value having type double. The presicion of type double is typically around 15 decimal digits, so adding 10 to 1e18 may not change the value of double.
You can add a cast to long long before addition to eliminate the issue in this case, but generally you should avoid using floating-point numbers to deal with integers.
#include <iostream>
int main(void) {
long long value = static_cast<long long>(1e18) + 10;
std::cout << value << '\n';
return 0;
}

How to overcome negative integer outputs in infinite fibonacci series in c++?

I tried making infinite fibonacci series in c++ but after few terms it is showing negative integers. Here's the code:
int main(){
long long int a{0};
long long int b{1};
long long int c{1};
cout<<a<<endl<<b<<endl;
while (true){
cout<<c<<endl;
a=b;
b=c;
c=a+b;
}
}
I guess its because of size limit of long long int, but is there any way I can print upto infinity like in python?
As others have mentioned, there is no standard type that has infinite precision. You will need to use a third-party library, or write your own class that has this functionality.
One such library that implements arbitrary precision integers is boost multiprecision.
Here is an implementation of computing the first 500 numbers:
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
int main()
{
using Int = boost::multiprecision::cpp_int;
Int a{0};
Int b{1};
Int c{1};
std::cout << a << std::endl << b << std::endl;
for (int i = 0; i < 500; ++i)
{
std::cout<< c << std::endl;
a=b;
b=c;
c=a+b;
}
}
Live Example

Unusal behaviour of sum in C++?

I'm writing a method to check if a number is palindrome or not. For example 12321 is palindrome and 98765 is not.
In my program I've used a recursive function to create exactly opposite of given number, like 56789 for 98765 and then checking if two numbers are equal or not. But I'm not getting exact opposite of 98765 which is 56789 instead I'm getting 56787.
Here's my code-
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
long int oppositeNum(int n){
if(n<10 && n>=0) return n;
if(n<0) return 0;
static int m=0;
int x = n%10;
long int num = oppositeNum(n/10);
cout << num << "\n";
return (num+ (x*pow(10,++m)));
}
int main(){
int n = 98765;
int oppNum = oppositeNum(n);
cout << oppNum;
if(oppNum==n){
cout << "Number is palindrome";
}else{
cout << "Number is not palindrome";
}
return 0;
}
I'm not getting the exact opposite of my original nnumber. the last digit is getting decremented by 1 every time is what I've observed.
Can anyone help?
I can not reproduce the result you are getting. Maybe it is a consequence of using the function pow
But in any case your function may not be called the second time for a different number because the static variable m is not reinitialized to 0. m continues to keep the value after the previous call of the function for a different number.
You can write the function without using the function pow.
Take into account that a reversed number can be too large to be stored an object of the type long because in some systems the type long has the same width as the type int. So I adjust instead of the type long to use the type long long as the return type.
Here you are.
#include <iostream>
long long int oppositeNum( int n )
{
static long long int multiplier = 1;
const int Base = 10;
int digit = n % Base;
return ( n /= Base ) == 0
? ( multiplier = 1, digit )
: ( n = oppositeNum( n ) , multiplier *= Base, digit * multiplier + n );
}
int main()
{
int n = 12321;
std::cout << n << " -> " << oppositeNum( n ) << '\n';
n = - 12321;
std::cout << n << " -> " << oppositeNum( n ) << '\n';
n = 98765;
std::cout << n << " -> " << oppositeNum( n ) << '\n';
n = -98765;
std::cout << n << " -> " << oppositeNum( n ) << '\n';
return 0;
}
The program output is
12321 -> 12321
-12321 -> -12321
98765 -> 56789
-98765 -> -56789
I changed only as much as it seemed neccessary. It still could use some tail recursion but this would probably required rewriting the whole algorithm.
long int oppositeNum(int n, int &m){
if(n<10) return n;
int x = n%10;
long int num = oppositeNum(n/10, m);
cout << num << "\n";
m *= 10;
return num + x * (long int)m;
}
long int oppositeNum(int n){
if(n<0) return 0;
int m = 1;
return oppositeNum(n, m);
}
What did I change:
Removed the static modifier from m and instead passing it by reference. This allows to use the function more than one time during the program execution. (Also it would allow to use the function by multiple threads at once but I guess this is not a concern here.)
Removed the floating point function pow and instead just multiplying the variable m by ten each iteration.
Added a wrapper for the recursive function so it still can be called with just one argument. Additionally this allow to check for negative numbers only once.
The main source of problem was the function pow. Because it works on floating point numbers, it may not give exact results. It depends on the compiler and the processor architecture but generally you shouldn't expect it to give an exact result. Rounding it to integer additionally increases the difference.
return (num + float(x*pow(10,++m)));
just do this and it will work. the ans is wrong cos the pow func is giving out 4999 and 5999 that is why it changes the units place.
Try this:
return round(num+ (x*pow(10,++m)));
Sometimes the pow function will return the approximated result. e.g. pow(10, 5) could be 99999.9999999, if you round it, you'll get 100000 else it takes the floor value (I think).

Wrong value being passed for unsigned long int in C++

I have a program which takes an unsigned long int as an input, and all subsequent functions should receive the value as such.
In the main function, however, when 18446744073709551557 is entered, it is returned as 34359738363435973836, and when the value is passed to another function, it is seen as 3435973836.
How come this happens?
EDIT:
Main function is as follows:
int main()
{
// initalise variables
std::list<unsigned long int> results;
unsigned long int n;
// request user input
std::cout << "Enter a number: ";
std::cin >> n;
std::cout << "You entered: " << n << std::endl;
// populate results list
results = primeFactors(n);
results.sort();
// display results
std::cout << "Factors for " << n << " are: ";
for (int i : results)
{
std::cout << i << " ";
}
return 0;
}
Function the value gets passed into:
std::list<unsigned long int> primeFactors(unsigned long int n)
{
// initialise variables
std::list<unsigned long int> factors;
bool complete = false;
unsigned long int ans1 = 0;
unsigned long int ans2 = 0;
std::cout << n;
(There's a lot of code in the second function, so I haven't included it all)
Your input number is far too large to store as an unsigned long int.
You can view the limits for various types here
I would suggest looking into using a library that can handle arbitrarily large numbers such as Boost.multiprecision
I don't think that 18446744073709551557 is a valid unsigned long int.
It crosses the limit already.
The limit of c++ datatype are here...
Try the value between limits. If then also doesn't work help us to see the code snippets and to detect the bugs.

C++ program to calculate the sum of all five-digit odd numbers?

I'm having a problem with the following simple code, I don't know why the output will become negative... The program is supposed to calculate the sum of all odd and five-digit numbers like 10001, 10003, 10005, etc.
#include <iostream>
using namespace std;
int main()
{
int num, sum = 0;
for (num = 10001 ; num <= 99999 ; num+=2){
sum += num;
}
cout << num << " " << sum;
return 0;
}
It means that there is an overflow of type int. That is this type can not represent the sum. I advice to declare variable sum like
long long int sum = 0;
After that you can compare the result with the maximum value stored in type int. For example
#include <limits>
//...
std::cout << std::numeric_limits<int>::max() << " " << sum << std::endl;;
Your int will likely overflow. Switch it to long
int num = 0;
long long sum = 0L;
Assuming you have a 4 byte int, the maximum value will be 2^31 - 1 == 2147483647. See this example
Your sum will come out to 2475000000 which will overflow.