Hello beautiful people,
I need a help with output of this program:
#include <stdio.h>
int main() {
int x,y;
scanf("%d %d",&x,&y);
int t = x^y;
int p = 0;
while (t > 0) {
p += t%2;
t /= 2;
}
printf("%d", p);
return 0;
}
I tried to write it down on paper and do some work by hand.
So i wrote this :
lets say for x = 2 and y = 4
first iteration:
p = 0 + 16mod2 which is equal to 0
t = 8
second iteration:
p = 0 + 8mod2 which is equal to 0
t = 4
third iteration:
p = 0 + 4mod2 which is equal to 0
t = 2
forth iteration:
p = 0 + 2mod2 which is equal to 0
t = 1
And output should be 0, but somehow when I run code I get 2.
Can someone help me out with this one please? And are there any other cases to consider, like what if x = 0, y = 0 or x and y are < 0 ?
The problem here, is that you assume that 2^4 == 16, when in fact, it is only 6, as the ^ operator, is actually an XOR.
You should be using
int t = pow(x, y)
int t = x^y;
Is not "x raised to the power of y". It's "x XOR y". T starts at 6 in your example.
As others have mentioned x^y is XOR operation, what you had in mind is :
#include <math.h>
....
int t = pow(x,y);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So there is a sequence of integers, {𝑎1, 𝑎2, 𝑎3, … } , the pattern of this sequence is that 𝑎𝑛 = 𝑎𝑛−1 + (𝑛 − 1) and 𝑎1 = 1. So if the first five elements in the sequence are: {𝑎1 = 1, 𝑎2 = 1 + 1 = 2, 𝑎3 = 2 + 2 = 4, 𝑎4 = 4 + 3 = 7, 𝑎5 = 7 + 4 = 11 … } . I am trying to write a program in C to ask the user to input an integer (an) to be the position index for this sequence and calculate the value of that position in the sequence. Like the user inputs 7 and it prints that the answer is 22? I have to use recursion and honestly don't even know where to go from that...
I think I am figuring it out, but I am pretty sure this is how it should work and yet it is off by exactly 1!
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num-1 + sum(num-1); // sum() function calls itself
else
return num;
}
If I give you a function that magically calculates a(n-1), you can easily calculate a(n) right?
int a(int n)
{
int previousA /*a(n-1)*/ = magic(); // magic() knows by itself which n to use
return previousA + n - 1;
}
What if I tell you that magic() is exactly the same as a(n-1)?
int a(int n)
{
int previousA /*a(n-1)*/ = a(n-1);
return previousA + n - 1;
}
Now, the only problem is that this kind of calling we would get an endless loop of calling - for a(3), a(2) is going to be called, then a(1), a(0), a(-1)... It'll never end.
What do we do?
Happily, we have an ending condition - a(1) is constant and equal to 1.
How do we insert it into the code? We insert a condition to check if n is 1, and if it is we simply return, with no further calls.
int a(int n)
{
if (n == 1)
{
return 1;
}
else
{
int previousA /*a(n-1)*/ = a(n-1);
return previousA + n - 1;
}
}
Or in short:
int a(int n)
{
return n == 1 ? a(n - 1) + n - 1 : 1;
}
(The ? and : are the syntax for a ternary operator. Read about it if you didn't understand them.)
For starters the name sum is not suitable because nothing is summarized. Maybe the function could be named like for example recursive_sequence.
The sequence is calculated for non-negative numbers. You have the base condition a[1] == 1 and the recursive condition a[n] = a[n-1] + ( n - 1 ). You should determine the value for the index equal to 0.
You have according to the conditions
a[1] == a[0] + ( 1 - 1 )
that is
a[1] == a[0] + 0
so a[0] is equal to 1.
Having this base condition for the index 0 you can write the function
unsigned int recursive_sequence(unsigned int n)
{
return n == 0 ? 1 : n - 1 + recursive_sequence(n - 1);
}
Pay attention to that the return type and the type of the parameter should be unsigned integer type.
Here is a demonstrative program
#include <stdio.h>
unsigned int recursive_sequence(unsigned int n)
{
return n == 0 ? 1 : n - 1 + recursive_sequence(n - 1);
}
int main( void )
{
const unsigned int N = 6;
for (unsigned int i = 0; i < N; i++)
{
printf("%u: %u\n", i, recursive_sequence(i));
}
return 0;
}
Its output is
0: 1
1: 1
2: 2
3: 4
4: 7
5: 11
I recently started programming and I was doing some exercises when I bumped into one that said:
Write a program that can calculate an approximate value of the e constant with the formula e=1+1/1!+1/2!+1/3!+... using while and if if necessary. You cannot use do...while or for.
I wrote my code and I could almost swear the program needs two while loops, but, as you may be guessing, it doesn't work properly. Here's my code:
#include<stdio.h>
int main()
{
float number=3, factorial=1, constant=0, counter=3, variable=0;
float euler=0;
while(counter>1)
{
variable = number;
while(number>1)
{
factorial = factorial*number;
number--;
} // number is now 0, or that's what I think
constant = (1/factorial)+constant;
counter--;
variable = variable-1; // variable is still number?
number = variable; // to have a variable called number again?
}
euler = constant+1; // the 1 in the original formula...
printf("e = : %f\n", euler);
return 0;
}
It doesn't display the correct answer, hope you can help me. Thanks a lot!
Your iteration is too few times. Iterate more to get more accurate value.
You will have to initialize factorial in each loop to calculate factorial in this way.
You forgot to add 1/1!.
Try this:
#include<stdio.h>
int main(void)
{
float number=30, factorial=1, constant=0, counter=30, variable=0;
float euler=0;
while(counter>1)
{
variable=number;
factorial = 1;
while(number>1)
{
factorial=factorial*number;
number--;
}//number is now 1
constant=(1/factorial)+constant;
counter--;
variable=variable-1;
number=variable;
}
euler=constant+1+(1/1.f);//the 1 and 1/1! in the original formula...
printf("e = : %f\n", euler);
return 0;
}
As pointed by #MikeCAT, various coding errors.
As OP's iteration count was low: 3 resulting in low accuracy. As all the terms are eventually added to 1.0 (missed by OP), once a term plus 1.0 is still 1.0, it is about time to quit searching for smaller terms. Typically about 18 iterations with typical double.
When computing the sum of a series, a slightly more accurate answer is available by summing the smallest terms first, in this case, the last terms as done by OP. This can be done using a recursive summation to avoid lots of factorial recalculation.
double e_helper(unsigned n, double term) {
double next_term = term/n;
if (next_term + 1.0 == 1.0) return next_term;
return next_term + e_helper(n+1, next_term);
}
double e(void) {
return 1.0 + e_helper(1, 1.0);
}
#include <stdio.h>
#include <float.h>
#include <math.h>
int main(void) {
printf("%.*f\n", DBL_DECIMAL_DIG - 1, e());
printf("%.*f\n", DBL_DECIMAL_DIG - 1, exp(1));
puts("2.71828182845904523536028747135266249775724709369995...");
}
Output
2.7182818284590451
2.7182818284590451
2.71828182845904523536028747135266249775724709369995...
#include <stdio.h>
#include <math.h>
int main()
{
printf("e = : %.20lf\n", M_E );
return 0;
}
C math library have constant M_E as Euler's number. But, this may not be what you want.
Finding eulers constant 'e' with the formula e = 1 + 1/1! + 1 /2! ....
only using while loop
For beginners
#include <stdio.h>
int main (void) {
float n =5 , fact = 1 , f , x = 0 , e ,i ; //taking input or n as 5 ,our formula now is e = 1+ 1/1! + 1/2! + 1/3! + 1/4! + 1/5! ; as the formula depends upon the input value of n
while(n >=1 ) { /* We need to find factorial of n no of values, so keeping n in a loop starting with 5....1 , atm n is 5 */
f = n ; // let f = n , i.e, f = 5
fact = 1 ;
while(f >= 1 ){ //This while loops finds the factorial of current n value , ie. 5 ;
fact = fact * f ;
f -- ;
}
i = 1 / fact ; // i finds the 1/fact! of the formula
x = i + x ; // x = i + x ; where x = 0 ; , This eq adds all the 1/fact values , atm its adding 1/ 5 !
n-- ; // n decrements to 4 , and the loop repeats till n = 1 , and finally x has all the 1/factorial part of the eulers formula
}
//exiting all the loops since, we now have the values of all the 1/factorial,i.e x : part of the eulers formula
e = 1 + x ; // eulers e = 1 + x , where x represents all the addition of 1/factorial part of the eulers formula
printf ("e : %f",e ); //Finally printing e
return 0 ;
}
Output :
e : 2.716667
I'm so confused here. Why this code of mine doesn't work as it SHOULD be..
Here's the code:
void print(int x) {
x = 140;
int i,total, length, value;
if (x < 10){
value = 0;
}
else {
int sum = 1;
for (i = 0 ; i < 10 ; i++){
total = 10 * sum;
sum = total;
length = x / total;
if (length < 10 && 1 <= length){
value = i+1;
break;
}
}
}
value = pow(10,value);
printf("%d\n",value);
}
Let me explain how the code should works first:
It takes an integer x and print out the highest power of 10 value it can be divided by.
So if X = 80, it should print 10 and if x = 12435, it should print 10000.
But this doesn't work with my code perfectly... if x = 140, it prints 99 but. if x = 1400, it prints 1000 then again, if x = 14000 it prints 9999 and if x = 140000 it prints 100000 and the sequence continues...
I've already tried exactly the same code in Java and it works perfectly!!
Why does it not works in C??
pow() is returning an double value, which you are casting to an integer. So instead of rounding it will be truncated.
You should try
value = round(pow(10,value));
I'm trying to understand a code here. I have been trying to understand it for quite a while now and since i can't completely understand it i'm turning to you for help.
#include<stdio.h>
int sumdig(int);
int main()
{
int a, b;
a = sumdig(123);
b = sumdig(123);
printf("%d, %d\n", a, b);
return 0;
}
int sumdig(int n)
{
int s, d;
if(n!=0)
{
d = n%10;
n = n/10;
s = d+sumdig(n);
}
else
return 0;
return s;
}
I can understand that the number will continue to pass the function until it reaches to 0 and then it returns 1 because 0==0 but after it returns 3 and finishes with a 6. That I don't understand. Remember i'm new to C
The first time round, with 123, n % 10 will evaluate to 3, and n / 10 will evaluate to 12, so it will return 3 + sumdig(12). sumdig(12) will, in the same way, return 2 + sumdig(1), sumdig(1) will return 1 + sumdig(0), and sumdig(0) will return 0, at which point it will stop. So overall, it will return 3 + 2 + 1, which is the sum of the digits in 123.
it is quite a basic recursive call...
the function sumdig is called in the following order:
1.sumdig(123):
d=3
n=12
s=3+sumdig(12)
2.sumdig(12):
d=2
n=1
s=2+sumdig(1)
3.sumdig(1):
d=1
n=0
s=1+sumdig(0)
4.sumdig(0): returns 0
3. return 1+0
2. return 2+1
1.returns 3+3
and that's how you get 6.
what is the complexity of the following c Function ?
double foo (int n) {
int i;
double sum;
if (n==0) return 1.0;
else {
sum = 0.0;
for (i =0; i<n; i++)
sum +=foo(i);
return sum;
}
}
Please don't just post the complexity can you help me in understanding how to go about it .
EDIT: It was an objective question asked in an exam and the Options provided were
1.O(1)
2.O(n)
3.O(n!)
4.O(n^n)
It's Θ(2^n) ( by assuming f is a running time of algorithm we have):
f(n) = f(n-1) + f(n-2) + ... + 1
f(n-1) = f(n-2) + f(n-3) + ...
==> f(n) = 2*f(n-1), f(0) = 1
==> f(n) is in O(2^n)
Actually if we ignore the constant operations, the exact running time is 2n.
Also in the case you wrote this is an exam, both O(n!) and O(n^n) are true and nearest answer to Θ(2^n) among them is O(n!), but if I was student, I'll mark both of them :)
Explanation on O(n!):
for all n >= 1: n! = n(n-1)...*2*1 >= 2*2*2*...*2 = 2^(n-1) ==>
2 * n! >= 2^n ==> 2^n is in O(n!),
Also n! <= n^n for all n >= 1 so n! is in O(n^n)
So O(n!) in your question is nearest acceptable bound to Theta(2^n)
For one, it is poorly coded :)
double foo (int n) { // foo return a double, and takes an integer parameter
int i; // declare an integer variable i, that is used as a counter below
double sum; // this is the value that is returned
if (n==0) return 1.0; // if someone called foo(0), this function returns 1.0
else { // if n != 0
sum = 0.0; // set sum to 0
for (i =0; i<n; i++) // recursively call this function n times, then add it to the result
sum +=foo(i);
return sum; // return the result
}
}
You're calling foo() a total of something like n^n (where you round n down to the nearest integer)
e.g.:
foo(3)will be called 3^3 times.
Good luck, and merry Christmas.
EDIT: oops, just corrected something. Why does foo return a double? It will always return an integer, not a double.
Here would be a better version, with micro-optimizations! :D
int foo(int n)
{
if(n==0) return 1;
else{
int sum = 0;
for(int i = 0; i < n; ++i)
sum += foo(i);
return sum;
}
}
You could have been a bit more clearer... grumble grumble
<n = ?> : <return value> : <number of times called>
n = 0 : 1 : 1
n = 1 : 1 : 2
n = 2 : 2 : 4
n = 3 : 4 : 8
n = 4 : 8 : 16
n = 5 : 16 : 32
n = 6 : 32 : 64
n = 7 : 64 : 128
n = 8 : 128 : 256
n = 9 : 256 : 512
n = 10 : 512 : 1024
number_of_times_called = pow(2, n-1);
Let's try putting in inputs, shall we?
Using this code:
#include <iostream>
double foo (int n) {
int i;
double sum;
if (n==0) return 1.0;
else {
sum = 0.0;
for (i =0; i<n; i++)
sum +=foo(i);
return sum;
}
}
int main(int argc, char* argv[])
{
for(int n = 0; 1; n++)
{
std::cout << "n = " << n << " : " << foo(n);
std::cin.ignore();
}
return(0);
}
We get:
n = 0 : 1
n = 1 : 1
n = 2 : 2
n = 3 : 4
n = 4 : 8
n = 5 : 16
n = 6 : 32
n = 7 : 64
n = 8 : 128
n = 9 : 256
n = 10 : 512
Therefore, it can be simplified to:
double foo(int n)
{
return((double)pow(2, n));
}
The function is composed of multiple parts.
The first bit of complexity is the if(n==0)return 1.0;, since that only generates one run. That would be O(1).
The next part is the for(i=0; i<n; i++) loop. Since that loops from 0..n it is O(n)
Than there is the recursion, for every number in n you run the function again. And in that function again the loop, and the next function. And so on...
To figure out what it will be I recommend you add a global ounter inside of the loop so you can see how many times it is executed for a certain number.