c++ calculation of long doubles giving inf or zero - c++

so I created a program that takes in two long double numbers and some a particular form of calculation on them. but the issue is, the output for me is inf or in some compilers, 0..
So the error only occurs when I enter exponential values like say I enter 1.11224e+2121 1.11224e+2121
then I get inf or 0 but if I get something like 2.4 5.9 I get proper value. How do I fix this?
here is my code
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main()
{
long double a,b,add=0,mean=0;
cin>>a>>b;
vector<long double> vector;
vector.push_back(a);
vector.push_back(b);
mean=(vector[0]+vector[1])/2;
for (int k = 0; k < 2; k++)
{
add= add+ pow((vector[k] - mean), 2);
}
cout<<add/2;
return 0;
}

Related

How can I make code more time-efficient that calculates 1's in binary representation of int?

I wrote this code for a problem that asks me to calculate the number of 1's in a binary representation of an integer number, and then find the next number which has the same exact number of 1's in its binary number.
I wrote code and it seemed to work just fine until the OJ gives an error:
time limit exceeded error.
I'd like some idea about how I could avoid this error.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int binary(int num){
int count=0;
vector <int> vec;
while(num!=0){
int rem=num%2;
num/=2;
vec.push_back(rem);
}
reverse(vec.begin(),vec.end());
for(int i=0;i<vec.size();i++){
if(vec[i]==1){
count++;
}
}
return count;
}
int main()
{
int looper,order=1;
cin>>looper;
while(looper--){
int num;
cin>>num;
int x=binary(num);
int next_num=num+1;
while(binary(next_num)!=x){
next_num++;
}
cout<<"Case "<<order<<": "<<next_num<<endl;
order++;
}
return 0;
}
This:
int next_num=num+1;
while(binary(next_num)!=x){
next_num++;
}
Is extremely inefficient. Consider your number is
1010101.....01111
Then the next bigger number with same number of 1s is
1010101.....11110
I'll leave it to you to realize the general pattern, the point is just that you dont need a loop to convert all numbers to binary and count the 1s. Instead you can directly construct the number in binary.
PS: std::bitset can come in handy when you need to get the binary representation.
You don't need to count 1's if you're just finding next number that has same numbers of 1's
You just need to swap 1 & 0 from right to left for once.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int binary(int num){
int count=0;
vector <int> vec;
while(num!=0){
int rem=num%2;
num/=2;
vec.push_back(rem);
}
reverse(vec.begin(),vec.end());
for(int i=0;i<vec.size();i++){
while(vec[0]!=vec[i]){
swap(vec[0],vec[i]);
}
// convert binary to decimal
// count = decimal number
return count;
}
int main()
{
int looper,order=1;
cin>>looper;
while(looper--){
int num;
cin>>num;
int x=binary(num);
cout<<"Case "<<order<<": "<<x<<endl;
order++;
}
return 0;
}

C++ Unable to get the correct answer for median value

Ok so I created a program that takes in a vector and calculates the median. Although im getting the correct median value for odd number, im not getting the same for even. here is my code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
bool check;
cout<<"Hello World";
vector<double> vec;
vec.push_back(2);
vec.push_back(6);
vec.push_back(8);
vec.push_back(62);
double median;
if(check==vec.size()%2)
{
median=(vec[vec.size() / 2 - 1] + vec[vec.size() / 2]) / 2;
}
else{
median=vec[(vec.size() / 2.0)];
}
cout<<median;
return 0;
}
so when i checked online, the correct answer should be 7 but I get 8.. And this happens only for the even number calculation.. what am i doing wrong i dont get it
I rewrote your code and cleaned up some unnecessary variable. I per-calculated the array size n and the midpoint centerElement. You do not want to repeatedly do this calculation specially in scenarios where you have a very large array.
I also removed the boolean variable check, which is completely unnecessary. You can find simply compare the output of modulus operation by comparing it with 0
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<double> vec;
vec.push_back(2);
vec.push_back(6);
vec.push_back(8);
vec.push_back(100);
auto n = vec.size();
auto centerElement = n/2;
double median;
if(n%2 == 0)
{
median=(vec[centerElement - 1] + vec[centerElement]) / 2;
}
else{
median=vec[(centerElement)];
}
cout<<median;
return 0;
}

How to remove the error related to modulus in the challenge 'Sam and sub-strings'?

I was doing a problem named Sam and sub-strings on hackerrank which you can look by clicking on the corresponding link.
Here is my code. I am sure that the logic of my program is correct as it works for smaller values (and also the sample test cases). The problem is with modulus and I am not able to get how to use modulus in this program correctly. Can anyone please help me (if possible, please tell when/where to use modulus in the program without editing the rest of my program)?
My submission gives correct results for testcases 0,1,2,3,12 and incorrect results for the rest.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
long long int n;
cin >> n;
vector<long long int> v1;
while (n!=0){
v1.push_back(n%10);
n=n/10;
}
long long int x=1,s1=0,sum=0;
for (long long int i=v1.size()-1;i>=0;i--){
s1+=x*v1[i];
x++;
sum=(sum+(s1*(long long int)pow(10,i))%1000000007)%1000000007;
}
cout << sum << endl;
return 0;
}
I suggest you treat the number as text when playing with digits.
int main()
{
std::string number_as_text;
std::cin >> number_as_text;
long long sum = 0;
const std::string::size_type length = number_as_text.length();
for (unsigned int index = 0; index < length; ++index)
{
long long s1 = (number_as_text[index] - '0') * (index + 1);
sum = sum * 10 + s1;
}
return 0;
}
You'll have to figure out where to put the mod 1000000007 in your program, if you need to.
Also, I recommend placing error handling in the code, especially when reading in the number. The function std::isdigit looks helpful.

too many collisions in random number generator collision test

I'm expecting lKolizji variable to be around 128, but it's much higher for large ammount of generated numbers and "boxes". The results for smaller numbers are good. I have no idea why is this happening. Here is my code with example parameters that give wrong answer. Example of good result(around 128) is int lPrzedzialow=1000000;
int iLiczb = 16000;
#include <iostream>
#include <gsl/gsl_rng.h>
#include <stdlib.h>
#include<cmath>
#include <algorithm>
using namespace std;
int main (void)
{
//Random number
unsigned int seed=2596524;
gsl_rng * r=gsl_rng_alloc (gsl_rng_mt19937);
gsl_rng_set(r,seed);
gsl_rng_env_setup();
//Parameters
int lPrzedzialow=10000000000;//number of boxes
int iLiczb = 1600000;//number of random numbers
int z,lKolizji=0;//lKolizji holds collision number
vector<int> lwKomorkach(iLiczb);//number of boxes of random numbers
long double dlPrzedzialu=1./(lPrzedzialow);
//number of box of a random number
for (int i = 0; i < iLiczb; i++)
{
lwKomorkach[i] = floor((gsl_rng_uniform (r)/dlPrzedzialu));
}
//sorting
sort( lwKomorkach.begin(), lwKomorkach.end() );
//how many collisions
for(z=0;z<=iLiczb-1;z++)
{
if(lwKomorkach[z+1]==lwKomorkach[z]){lKolizji++;}
}
double pdf[lKolizji];
pdf[0]=exp(-128);
double spdf=exp(-128);
for(int h=1;h<lKolizji;h++){
pdf[h]=pdf[h-1]*128./(h);
spdf+=pdf[h];
}
double pwyzsze=1.-spdf;
cout<<endl<<lKolizji<<" "<<spdf<<" "<<pwyzsze<<endl;
gsl_rng_free (r);
return 0;
}
This number: 10000000000, is too big for a 32 bit int. In fact, it is equivalent to 1,410,065,408, approx 1/7th of the size you believe it to be.

Error when using 'int' datatype even when number is not a decimal

I understand the difference between int, float and double data types. But I have observed that sometimes when I use 'int' data type in a mathematical operation comprising of only integer values, it gives a result one less than the right answer. However, it's correct when I use float or double.
Take a look at the code below.
#include <iostream>
#include<math.h>
using namespace std;
int getno(int num)
{
int x,i;
float y=0;
for(i=0; i<4; i++)
{
x=num%10;
y=y+(x*pow(10,i));
num=num/10;
cout<<x*pow(10,i)<<endl;
cout<<y<<endl;
}
return y;
}
main()
{
int n;
cin>>n;
cout<<getno(n);
}
if I change the datatype of y to int, it gives a wrong answer by one. i.e 12345 would result in 2344 instead of the required 2345. Why is that happening?
I suppose "pow(10, i)" returns a bit less value than 10^i, let say 999.9999999 for i=3.
And afterwards it's truncated by float->int conversion into 99. As a result, we can loss 1 at every "y=.." operation.
I don't see your issue:
#include <iostream>
#include <math.h>
using namespace std;
int getno(int num)
{
int x,i;
float y=0;
for(i=0; i<4; i++)
{
x=num%10;
y=y+(x*pow(10.0f,(float)i));
num=num/10;
cout<<x*pow(10.0f,i)<<endl;
cout<<y<<endl;
}
return (int)y;
}
int main(void)
{
int n=12345;
// cin>>n;
cout<<getno(n);
return 0;
}
and the output is:
5
5
40
45
300
345
2000
2345
2345
I just cleaned up the warnings about int to float conversion on your call to pow and explicitly convert your return type.