
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Code to Count Children Who Will Get Ball After Each Throw
Suppose we have a number n. Few kids are standing on a circle. They are numbered from 1 to n, they are in clockwise order and the child number 1 is holding the ball. First the child number 1 throws the ball to the next one clockwise, Then the child number 2 throws the ball to the next but one child, (to the child number 4), then the fourth child throws the ball to the child number 7 and so on. When a ball is thrown it may pass the beginning of the circle. Not all the children get the ball during the game. If a child doesn't get the ball, We have to find the numbers of the children who will get the ball after each throw.
So, if the input is like n = 10, then the output will be [2, 4, 7, 1, 6, 2, 9, 7, 6].
Steps
To solve this, we will follow these steps −
p := 1 for initialize i := 1, when i < n, update (increase i by 1), do: p := p + i p := p mod n if not p is non-zero, then: p := n print p
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void solve(int n){ int p = 1; for (int i = 1; i < n; i++){ p += i; p %= n; if (!p) p = n; printf("%d, ", p); } } int main(){ int n = 10; solve(n); }
Input
10
Output
2, 4, 7, 1, 6, 2, 9, 7, 6,