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 2 years ago.
Improve this question
I have to do a code that print the average of the numbers in an array. For sum, I use a function that I used in another time to calculate the recursive sum, and only divide by n later. But it doesn't work.
Why should I do?
int aveg(int *a, int n){
if (n == 0){
return 0;
}
else{
return ((aveg(a, n - 1) + a[n-1]) /n);
}
}
Because (a + b + c)/3 != ((a/1 + b)/2 + c)/3.
Instead, you can calculate the sum recursively, then divide by n at the very end.
You can recursively compute the mean (with zero based indices) as follows:
A possible implementation is:
#include <stdio.h>
#include <stddef.h>
double mean(const double a[],const size_t n)
{
if(n==0)
return 0;
return (a[n-1]+(n-1)*mean(a,n-1))/n;
}
int main()
{
double a[]={1,2,3,4,5};
size_t n = sizeof(a)/sizeof(*a);
printf("mean: %f\n",mean(a,n));
}
Compared to your solution:
return ((aveg(a, n - 1) + a[n-1]) /n);
you forgot a (n-1) factor:
return (a[n-1]+(n-1)*mean(a,n-1))/n;
It works like calling itself (function) again and again until you get the true or your desire output.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
I've got a task in my lesson to write a function that will check if a number is prime, it will return 1 if it is and 0 if it is not and all of that to do recursively. the function will look like that :int isPrime(int num);
I've tried everything and searched everywhere and came to the conclusion that it's possible only with static int which I did not learn yet so can't use it or with two parameters.
does anyone know if there is a way to solve it with only one parameter ad no static int?
thanks.
This was a trick question: you are supposed to use recursion, but unless you are barred from using loops, a classic solution with a for loop can be made to comply with the recursion requirement.
Here is a function isPrime that has a single argument and uses a classic loop and recursion to test prime divisors:
int isPrime(int n) {
if (n <= 1)
return 0;
if (n % 2 == 0)
return n == 2;
for (int p = 3; p * p <= n; p += 2) {
if (isPrime(p) && n % p == 0)
return 0;
}
return 1;
}
The above code only performs the modulo operation for prime divisors. It is a false optimisation because it is actually more costly to determine if p is prime with a recursive call than to compute n % p.
So here is my solution to this questionable assignment. It contains only functions taking one int argument and uses recursion and no loop:
#include <iostream>
#include <functional>
std::function<bool(int)> isPrime(int x) {
return [x](int p) {
if (x <= 2) return true;
return (p % (x - 1) != 0) && (isPrime(x - 1)(p));
};
}
int main() {
if (isPrime(19)(19)) std::cout << "is prime" << std::endl;
}
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 3 years ago.
Improve this question
Given g(x) = cos(log(2.21-x)) and that x = 0.99, estimate the value given by the nested g(g(g(x)... equation as the nesting approaches infinity (you don't have to actually go to infinity, but just set up a way to recurse this nesting n times or so).
I've tried some basic stuff like g(x) = cos(log(2.21-x))
and then creating a for loop defined by g(x) = g(g(x)). None of this works.
In these attempts I've gotten end of void errors and overflow errors. If anyone can figure out if this question is viable in C, even though C doesn't support "nested" functions, I will be amazed and very thankful.
Recursive solution:
// assuming g(double x) is already defined and returning a double value
double get_g_x_to_n(double x, int n) {
if (n > 1)
return g (get_g_x_to_n(x, n - 1);
return g(x);
}
get_g_x_to_n(0.99, 1024);
Iterative solution:
// assuming g(double x) is already defined and returning a double value
double get_g_x_to_n(double x, int n) {
double cur_operand = x;
for (int i = 0; i < n; i = i + 1) {
cur_operand = g(cur_operand);
}
return cur_operand
}
get_g_x_to_n(0.99, 1024);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
Now im having problems with the new code in terms of compiling. I have two great answers but chux's answer is addressed to rectify my code . So by his/her directions my new code is:
#include <math.h>
#include <conio.h>
int main()
{
int n,i,r;
printf("Enter A Number to know its prime or non prime");
scanf("%d",&n);
for(i=2;i<=n-1;i++)
{
if(n%i==0)
{r==1;
break;
}
}
if(r==1)
printf("%d is a non-prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
But on the output it show as 87 is a prime number. I don't know why. But can someone spot my mistake?
At few problems
Assignment vs. compare
if (r=1) assigns 1 to r, so if (r=1) is always true. Certainly a compare was needed, #Ry
// if (r=1)
if (r == 1)
No early break
OP's code: The value of r depends on the last iteration. Certainly once a factor is found, loop should exit.
for(i=2;i<=n-1;i++) {
if(n%i==0)
// r=1;
{ r = 1; break; }
else
r=0;
}
Incorrect functionality for n == 0,1
All values n < 2 incorrectly report as prime.
Inefficient
Code performs up to n loops. Only need to perform sqrt(n) loops. Tip: Do not use floating point math here for an integer problem.
// for(i=2;i<=n-1;i++)
for(i = 2; i <= n/i; i++)
Alternate
Only peek if you must code.
First off, " ... conio.h is a C header file used mostly by MS-DOS compilers to provide console input/output. It is not part of the C standard library or ISO C .." I was able to get the code to compile without that library file, so you may wish to consider removing it. As for as the code goes, well here is what I came up with:
#include <math.h>
#include <stdio.h>
int isPrime(int value) {
int i = 2;
for(; i < value; i++) {
if((value % i) == 0) {
return 0;
}
}
return value > 1;
}
int main(void){
int n=0,i=0, r=0;
char * s;
printf("\nPlase enter a number to learn if it is prime:");
scanf("%d",&n);
r = isPrime(n);
printf("\n%d is ", n);
s = (r==0)? " not a prime number" : "a prime number";
puts(s);
return 0;
}
After the user inputs a number, the code checks whether it is prime by calling the function isPrime(), a function that returns an int. isPrime is a simple function that attempts to factor a number.
See here for similar live code that I devised.
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 4 years ago.
Improve this question
I want to write (a^n-1) in c programming. I wrote pow(a,n-1) and the output is
wrong. How can I solve this problem? Thanks.
Here is my code:
#include <stdio.h>
#include<math.h>
int main() {
float a, r,n;
float sum = 0;
a = 1.04*pow(a, n-1);
r = 1.02*pow(1.04,-1);
n = 2;
sum = 360000*pow(1.04,n)-50000*(a * (1 - pow((r), n ))) / (1- (r));
printf("\n%.2f", sum);
return 0;
}
The correct output should be 286376 but the program showed 2903773
Every C program executes line by line. So, at the time when compiler came on
a = 1.04*pow(a, n-1);
this line, variable a and n was not assigned with any value, resulted in giving you a garbage value...
So, the problem is, you had not assigned values in variables, and still, you were using them.
You have to first assign values in variables before using them. Otherwise, they will pick any garbage value from memory (Any Random number).
Assign value in a and n and try again.
Edit: As chux's comment suggests, if your program is supposed to give 286376 as output, then value of a should be 1 and value of n should be 2.
So, your correct code would be this:
#include <stdio.h>
#include <math.h>
int main() {
float a=1, r, n=2;
float sum = 0;
a = 1.04*pow(a, n-1) ;
r = 1.02*pow(1.04,-1);
sum = 360000*pow(1.04,n)-50000*(a * (1 - pow((r), n ))) / (1- (r));
printf("\n%.2f", sum);
return 0;
}
pow(a, n-1) translates into exp(log(a) * (n-1)) which isn't precisely the same.. You can try to round the output like this:
round(pow(a, n-1))
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 6 years ago.
Improve this question
the output numbers are wrong why ?
the program is used to get factorial of a number using recursion
and if you know sites to practice more examples I will be thankful for you
#include <stdio.h>
#include <stdlib.h>
int factorial(int a);
int main()
{
int n,x;
printf("enter ur number ");
scanf("%d",&x);
n=factorial(x);
printf("the factorial = %d",n);
return 0;
}
int factorial(int a)
{
int fac;
if(a<=1)
{
if (a<1)
{
fac=0;
}
return fac;
}
printf("the number = %d\n",a);
printf("the factorial = %d\n",fac);
fac = a * factorial(a-1);
This will always return 0, because the last fac will always be 0 and it multiplies all the other results. Change that to
if(a<1)
fac=1;
Also indent your code properly.