Home > Backend Development > C++ > C program: Solve the stop problem

C program: Solve the stop problem

WBOY
Release: 2023-09-11 20:17:02
forward
1086 people have browsed it

C program: Solve the stop problem

Problem Statement- A program to find a train stopping at r stations out of n stations in such a way that no two stops are consecutive.

Explanation of the problem

This program will count the number of ways the train can stop, that is, the arrangement. Here, the train will travel from point X to Y. Between these points, there are n sites. The train will stop at r stations among these n stations, provided that when stopping at r stations, the train should not stop at two consecutive stations.

This permutation can be found using the straightforward npr formula.

Let us give a few examples, p>

Input : n = 16 , r = 6
Output : 462
Copy after login

Explanation - Use the permutation formula given below to find 6 stations out of 16 stations where the train can serve Number of ways to dock:

npr or p(n, r) = n! ∕ (n-r)!

Algorithm

Input  : total numbers of stations n and number of stations train can stop r.
Step 1 : For values of n and r calculate the value of p(n,r) = n! / (n-r)!
Step 2 : print the value of p(n,r) using std print method.
Copy after login

Example

Live demonstration

#include<stdio.h>
int main(){
   int n = 16, s = 6;
   printf("Total number of stations = %d</p><p>Number of stopping station = %d</p><p>", s, n);
   int p = s;
   int num = 1, dem = 1;
   while (p!=1) {
      dem*=p;
      p--;
   }
   int t = n-s+1;
   while (t!=(n-2*s+1)) {
      num *= t;
      t--;
   }
   if ((n-s+1) >= s)
      printf("Possible ways = %d", num / dem);
   else
      printf("no possible ways");
}
Copy after login

Output

Total number of stations = 16
Number of stopping station = 6
Possible ways = 462
Copy after login

The above is the detailed content of C program: Solve the stop problem. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template