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.
Related
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 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
While running the following lines of code:
int i,a;
for(i=0;i<=4;i++)
{
a=pow(10,i);
printf("%d\t",a);
}
I was surprised to see the output, it comes out to be 1 10 99 1000 9999 instead of 1 10 100 1000 10000.
What could be the possible reason?
Note
If you think it's a floating point inaccuracy that in the above for loop when i = 2, the values stored in variable a is 99.
But if you write instead
a=pow(10,2);
now the value of a comes out to be 100. How is that possible?
You have set a to be an int. pow() generates a floating point number, that in SOME cases may be just a hair less than 100 or 10000 (as we see here.)
Then you stuff that into the integer, which TRUNCATES to an integer. So you lose that fractional part. Oops. If you really needed an integer result, round may be a better way to do that operation.
Be careful even there, as for large enough powers, the error may actually be large enough to still cause a failure, giving you something you don't expect. Remember that floating point numbers only carry so much precision.
The function pow() returns a double. You're assigning it to variable a, of type int. Doing that doesn't "round off" the floating point value, it truncates it. So pow() is returning something like 99.99999... for 10^2, and then you're just throwing away the .9999... part. Better to say a = round(pow(10, i)).
This is to do with floating point inaccuracy. Although you are passing in ints they are being implicitly converted to a floating point type since the pow function is only defined for floating point parameters.
Mathematically, the integer power of an integer is an integer.
In a good quality pow() routine this specific calculation should NOT produce any round-off errors. I ran your code on Eclipse/Microsoft C and got the following output:
1 10 100 1000 10000
This test does NOT indicate if Microsoft is using floats and rounding or if they are detecting the type of your numbers and choosing the appropriate method.
So, I ran the following code:
#include <stdio.h>
#include <math.h>
main ()
{
double i,a;
for(i=0.0; i <= 4.0 ;i++)
{
a=pow(10,i);
printf("%lf\t",a);
}
}
And got the following output:
1.000000 10.000000 100.000000 1000.000000 10000.000000
No one spelt out how to actually do it correctly - instead of pow function, just have a variable that tracks the current power:
int i, a, power;
for (i = 0, a = 1; i <= 4; i++, a *= 10) {
printf("%d\t",a);
}
This continuing multiplication by ten is guaranteed to give you the correct answer, and quite OK (and much better than pow, even if it were giving the correct results) for tasks like converting decimal strings into integers.
I want to find the number of zeroes in a factorial using Cpp. The problem is when I use really big numbers.
#include <stdio.h>
#include <math.h>
long zeroesInFact(long n)
{
long double fact=1;
long double denominator=10.00;
long double zero=0.0000;
long z=0;
printf("Strating loop with n %ld\n",n);
for(int i=2;i<=n;i++)
{
fact=fact*i;
printf("Looping with fact %LF\n",fact);
}
printf("Fmod %lf %d\n",fmod(fact,denominator),(fmod(fact,denominator)==zero));
while(fmod(fact,denominator)==zero)
{
fact=fact/10;
z++;
}
printf("Number of zeroes is %ld\n",z);
return z;
}
int main()
{
long n;
long x;
scanf("%ld",&n);
for(int i=0;i<n;i++)
{
scanf("%ld",&x);
printf("Calling func\n");
zeroesInFact(x);
}
return 0;
}
I think the problem here is that
fmod(fact,denominator)
gives me the correct answer for factorial of 22 and denominator as 10.00 (which is 0.000).
But it gives me the wrong answer for factorial of 23 and denominator as 10.00
Consider this your first lesson in numeric precision. The types float, double, and long double store approximations, not exact values, which means they are typically unsuitable for this sort of calculation. Even when they have enough precision for correct answers, you're still usually better off using integer numeric types instead, like int64_t and uint64_t. Sometimes you even even have a 128-bit integer type available. (e.g. __int128 might be available with Microsoft Visual Studio)
Honestly, I think you were lucky to get the right answer for 18! through 22!.
If long double truly is quadruple precision on your platform, you should be able to compute up to 30!, I think. You made a mistake when you used fmod -- you meant to use fmodl.
Your second lesson in precision is that when you need a lot of it, your basic data types simply aren't good enough. While you can write your own data types, you're probably better off using a pre-existing solution. The Gnu Multiple Precision Arithmetic Library (GMP) is a good, and fast one you can use in C/C++.
Alternatively, you could switch languages -- e.g. pythons integer data type is arbitrary precision (but not as fast as GMP), so you wouldn't even have to do anything special. Java has the BigInteger class for doing such computations.
Your third lesson is precision is to find ways to do without. You don't actually need to compute 23! in its full glory to find the number of trailing zeroes. With care, you can organize your calculation to discard extra precision you don't need. Or, you can switch to an entirely different method of obtaining this number, such as what Rob was hinting at in his comment.
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/