i am using code block for learning c. my code is
#include<stdio.h>
#include<math.h>
int main()
{
int x;
x = pow(5,2);
printf("%d", x);
}
Output is 25
When i am using this code
#include<stdio.h>
#include<math.h>
int main()
{
int x,i,j;
printf("please enter first value");
scanf("%d", &i);//5
printf("please enter second value");//2
scanf("%d", &j);
x = pow(i,j);
printf("%d", x);
}
Output is 24
what is wrong here? i am just taking value using scan function and also using pow function in a same way.
I suspect you have a naive implementation of pow in your libm (I get 25, as it should be). If that computes pow(x,y) as exp(y*log(x)) for positive x without checking for (small) integral exponents and treating them specially, you get
Prelude> 2 * log 5
3.2188758248682006
Prelude> exp it
24.999999999999996
a double result slightly smaller than 25, so when that is converted to int it is truncated to 24.
To check, assign the result of pow(i,j) to a double and print that out.
With hardcoded pow(5,2), the compiler (most likely, it's what gcc does even without optimisation) computes the result during compilation exactly.
Try changing initialization to this:
int x=-1 ,i=-1 ,j=-1;
And last print to this:
printf("pow(%d, %d) == %d\n", i, j, x);
That should give good hint about the problem. Also, check return values of scanf, they should return number of items read, ie. 1 with code above.
It's almost certain, that you entered invalid input for scanf, and i or j were left uninitialized, and that 24 is just garbage value.
Also, compile with warnings enabled, and fix them (like, add return 0; to end of main).
Your code correctly gives 25 on my windows x64.
You probably needs to run it again see if you just read it wrong...
The missing "return 0;" is not the problem here.
If, anything, could ever go wrong,
you can try adding
fflush(stdin);//or out
after very scanf and printf.
If any of the flushes solves your problem, you know what is going wrong.
It seems that there is nothing wrong with the second program, except that you must add at the end
return 0;
If you read the value j with 2 then the result will be just 25.
Using your code i got result 25 which is correct.
Although Try changing the data type of result such as float or double.
Related
I set up a string filled solely with numbers and using a for loop iterated through it in order to add them together mathematically (Wanted to see if the language would allow this), as a result I got some weird Numbers as the result. Can someone explain why this is happening?
int main()
{
std::string word = "2355412";
for (int i = 0; i<word.size(); i++){
int sum = word[i]+word[i+1];
std::cout << sum << std::endl;
}
return 0;
}
The code when run results in:
101
104
106
105
101
99
50
Due to the way I wrote my code I also believe that it should have resulted in an out of bounds error due word[i+1] on the final value resulting in the calling of a value that does not exist. Can someone explain why it did not throw an error?
The value you get is not what you expect because it is the sum of the ascii code corresponding to the characters you are summing, it's not converted into their value by default.
Also, as mentioned by other, string::operator[] doesn't check if you are trying to reach an out of bound value. In this case, you read 0 because you reached the string termination character \0 which happen to be 0.
it should have resulted in an out of bounds error
string::operator[] doesn't check bounds, it assumes you have. If you call it with an out of bounds index, the entire behaviour of your program is undefined, i.e. anything can happen.
It sounds like you want string::at, which does check bounds, and will throw std::out_of_range
In the below code, if I use just factorial(n), it gives the correct output (120), but when I use factorial(factorial(n)), the result is 0. Could someone please explain what is going wrong?
int factorial(int);
int main()
{
int n = 5; // number of terms
cout<<endl<<"The factorial is:"<<factorial(factorial(n));
return 0;
}
int factorial(int x)
{
if(x==1)
return 1;
else
return x * factorial(x-1);
}
Your problem is that you're hitting integer overflow.
As you noted the factorial of 5 is 120.
So factorial(factorial(5)) is the same as factorial(120). As you can see you're not passing the factorial function as argument to the outer factorial. You're passing the result of the call to the inner factorial as argument to the outer factorial.
The code is equivalent to this :
int result = factorial(5); // result = 120
factorial(result); // factorial (120)
The problem is that the factorial of 120 is a really big number, a number of almost 200 digits
Now this is way bigger than what an int can store. Or even a long long unsigned int. You need specialized libraries to handle arbitrarily big numbers.
factorial(factorial(5));
is effectively evaluated as if were written
temp = factorial(5); factorial(temp);
Based in the fact that we know temp will be set to 120 (we were told the function works for argument 5), the question is what happens in factorial(120).
The answer is: it overflows the maximum value of an integer.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have been trying to solve http://www.spoj.com/problems/SCUBADIV/ question at SPOJ. I have come up with a recursive DP solution.
I am using knapsack approach with a 3 dimensional array to store the number of cylinders, required oxygen weight, and nitrogen weight. At each recursive step I'm checking for the amount of oxygen and nitrogen yet to be filled. If it is negative, it's as good as zero.
#include<bits/stdc++.h>
using namespace std;
#define inf 99999999
int n;
vector<int> o;
vector<int> ni;
vector<int> w;
int ow;
int nw;
int knapsack(int n,int ow,int nw); // n - number of cylinders,ow-wt. of oxygen
// nw-wt. of nitogen.
int main(){
int t;
scanf("%d",&t);
while(t--){
int i;
scanf("%d %d",&ow,&nw);
scanf("%d",&n);
o.resize(n);
ni.resize(n);
w.resize(n);
for(i=0;i<n;i++)
scanf("%d%d%d",&o[i],&ni[i],&w[i]); // o[i] storing wt. of oxygen cylinders
int res = knapsack(n,ow,nw); //ni[i] storing wt. of nitrogen cylinders
printf("%d",res);
}
return 0;
}
int knapsack(int n,int ow,int nw){
int dp[n+1][ow+1][nw+1];
memset(dp,inf,sizeof (dp)); //setting value of array to inf to get minimum weight
int i;
for(i=0;i<n;i++)
dp[i][0][0]=0;
if(dp[n][ow][nw]!= inf)
return dp[n][ow][nw];
else if (ow - o[n-1]>=0 && nw - ni[n-1]>=0)
return dp[n][ow][nw]= min(knapsack(n-1,ow,nw),w[n-1]+knapsack(n-1,ow-o[n-1],nw-ni[n-1]));
else if(ow -o[n-1]<0 && nw - ni[n-1] >=0)
return dp[n][ow][nw]=min(knapsack(n-1,0,nw),w[n-1]+knapsack(n-1,0,nw-ni[n-1]));
else if(ow-o[n-1]>=0 && nw-ni[n-1]<0)
return dp[n][ow][nw]=min(knapsack(n-1,ow,0),w[n-1]+knapsack(n-1,ow-o[n-1],0));
else if(ow-o[n-1]<0 && nw-ni[n-1]<0)
return dp[n][ow][nw]= knapsack(n-1,0,0);
}
This code is not giving the desired result (it's giving -1). Is the approach correct ?
There is a problem with this code:
int dp[n+1][ow+1][nw+1];
memset(dp,inf,sizeof (dp));
The memset() function sets a byte pattern, not a value. Since inf is a larger-than-a-byte value, it is essentially doing inf % 256 and initializing all the bytes in dp[][][] to that value. This is further complicated by dp[][][] being of base type int, so 4 bytes set to the same byte value is something unexpected.
In the case of your value for inf, of 99999999, the byte value will be 0xff, and so all the ints in dp[][][] will be set to -1.
I don't know if this is expected, but it looks like it could be a mistake.
Let M(x, O, N) be the minimum weight of cylinders that will provide O liters of oxygen and N liters of nitrogen by choosing from only cylinders 1 to x. Let O(x), N(x), and W(x) be the amount of oxygen and nitrogen available in the x'th cylinder and the cylinder's weight respectively. Then either we choose to use the x'th cylinder or we don't:
M(x, O, N) = min( W(x) + M(x - 1, O - O(x), N - N(x)), M(x - 1, O, N) )
The base case occurs when we have no cylinders at all.
M(0, O, N) = 0 if O <= 0 and N <= 0, infinity otherwise
I won't be reading your unformatted, cryptically written code to figure out whether it implements this correctly. I will say memset can only be used to set bytes to a given value. Your call is not doing what you think. Additionally, your recursive procedure returns junk if execution reaches the end of the if chain.
Work a small example by hand. Run your code either in a debugger or with printfs inserted to show what's going on. Figure out where its actual execution diverges from your hand calculation.
Yes, it is possible to solve this problem with a recursive approach, but this is not how to do it. There are multiple problems with the code, and 'obviously' it will return -1. The question is I shall try to answer is: tell me some of the things wrong with this code.
Variable names like dp obscure the meaning of the code. Give them meaningful names!
Don't resize a vector and read into a pointer. Read values and push them onto the vector.
Print out the data to ensure you read it right.
The memset function fills with bytes, in this case -1. Use a loop to initialise ints.
The first if statement can only ever return 0 or -1 (or inf once you fix the init). As it is the other code will not be executed.
Assigning a value into dp is of no effect, since it is in automatic storage (on the stack).
I don't understand the chain of if statements. Explain them.
There is no else so the function can fall off the end.
Best to rewrite, debug, and if it still doesn't work come back with something we can read.
Input
The input begins with two positive integers n k (n, k<=10^7). The next n lines of input contain one positive integer ti, not greater than 10^9, each.
Output
Write a single integer to output, denoting how many integers ti are divisible by k.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
My Code:
#include <iostream>
using namespace std;
int main()
{
long long n,k, i;
cin>>n;
cin>>k;
int count=0;
for(i=0;i<n;i++)
{
int z;
cin>>z;
if(z%k == 0) count++;
}
cout<<count;
return 0;
}
Now this code produces the correct output. However, its not being accepted by CodeChef(http://www.codechef.com/problems/INTEST) for the following reason: Time Limit Exceeded. How can this be further optimized?
As said by caleb the problem is labeled "Enormous Input Test" so it requires you to use some better/faster I/O methods
just replacing cout with printf and cin with scanf will give you an AC but to improve your execution time you need to use some faster IO method for example reading character by character using getchar_unlocked() will give you a better execution time
so you can read the values by using a function like this , for a better execution time.
inline int read(){
char c=getchar_unlocked();
int n=0;
while(!(c>='0' && c<='9'))
c=getchar_unlocked();
while(c>='0' && c<='9'){
n=n*10 + (c-'0');
c=getchar_unlocked();
}
return n;
}
The linked problem contains the following description:
The purpose of this problem is to verify whether the method you are
using to read input data is sufficiently fast to handle problems
branded with the enormous Input/Output warning. You are expected to be
able to process at least 2.5MB of input data per second at runtime.
Considering that, reading values from input a few bytes at a time using iostreams isn't going to cut it. I googled around a bit and found a drop-in replacement for cin and cout described on CodeChef. Some other approaches you could try include using a memory-mapped file and using stdio.
It might also help to look for ways to optimize the calculation. For example, if ti < k, then you know that k is not a factor of ti. Depending on the magnitude of k and the distribution of ti values, that observation alone could save a lot of time.
Remember: the fact that your code is short doesn't mean that it's fast.
I am trying to give a shot at Project Euler problem 3 until codeblocks or whatever caused it pissed me off. This is my code, What is wrong with it? I guess more of a bug?
#include <iostream>
using namespace std;
int main()
{
int x=0;
for(int y=0;y<=10;y++)
{
if(13195%x==0)
{
cout<<"I don't know why the program crashes!";
}
}
}
You can't use a 0 as the second operand while doing / or %. What you're essentially saying is "Hey divide by 0 and give me the remainder." Please see the following:
Can't Mod Zero?
Modulus operator divides it by zero and next finds the remainder, thus you will get divide by zero error
x must not be equal to 0 otherwise division by zero.
Just think how many zeroes in 13195?
x = 0. Dividing a number with zero will crash your code. Make sure x is not 0 before 13195 % x.
The operation A modulo B is defined as: the remainder of the division of A by B.
In your code, you have B=0 which means you are trying to divide by zero.