Question

#include <stdio.h>    int josephus(int n, int k) {   if (n == 1)     return 1;   else...

#include <stdio.h>
  
int josephus(int n, int k)
{
  if (n == 1)
    return 1;
  else
    /* The position returned by josephus(n - 1, k) is adjusted because the
       recursive call josephus(n - 1, k) considers the original position 
       k%n + 1 as position 1 */
    return (josephus(n - 1, k) + k-1) % n + 1;
}
  
// Driver Program to test above function
int main()
{
  int n = 14;
  int k = 2;
  printf("The chosen place is %d", josephus(n, k));
  return 0;
}

this is a c source code to find the solution of the "Josephus problem"
but the problem is that this code only gives me the final outcome only,
what I want is to tweak this code and make it print all the outcomes from the begining until the final answer
I want the answer with explaination please

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

#include <stdio.h>

int josephus(int n,int k)
{
int a;
if(n==1)
return 1;
else

{
int a;
a=(josephus(n-1,k)+k-1)%n+1;
printf("%d\n",a);
return a;
}
}
int main()
{
int n=14;
int k=2;
printf("The chosen place is %d",josephus(n,k));
return 0;
}

Inorder to print the value at each recursive function call,we need to store the value into a variable.
We are printing that.And we are returning the stored value after each function call.
The final value is returned to the main function.

Thank you

Add a comment
Know the answer?
Add Answer to:
#include <stdio.h>    int josephus(int n, int k) {   if (n == 1)     return 1;   else...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT