- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Numbers with N digits which consists of even number of 0's in C++
We are given a number N as input. The goal is to find all N digit numbers that have an even number of 0’s as digits. The number also could have preceding zeros like in case of N=3 numbers included will be 001,002,003….010….so on.
Let us understand with examples.
Input − N=4
Output − Count of no. with N digits which consists of even number of 0's are − 7047
Explanation − All 4 digits numbers would be like −
Smallest will be 0000, then 0011,0012,0013,0014…..Highest will be 9900.
Input − N=5
Output − Count of no. with N digits which consists of even number of 0's are − 66383
Explanation − All 5 digit numbers would be like −
Smallest will be 00001, then 00002,00003,00004…..Highest will be 99900.
The approach used in the below program is as follows
We will first calculate the total N digit numbers that are T=10N-1. Then calculate all N digit numbers with odd 0’s as digits, that is O=10N-8N . The remaining numbers with Even 0’s in digits will be T-O/2.
Take an integer N as input.
Function count_even(int N) takes N and returns the count of N digit numbers with even 0’s.
Total N digit numbers are total=pow(10,N)-1
Total N digit numbers with odd 0’s in digit are odd=pow(10,N)-pow(8,N).
Leftover even 0’s in digit are even=total-odd/2.
Return even as a count of N digit numbers with even numbers of 0’s.
Example
#include <bits/stdc++.h> using namespace std; int count_even(int N){ int total = pow(10, N) - 1; int odd = pow(10, N) - pow(8, N); int even = total - odd / 2; return even; } int main(){ int N = 3; cout<<"Count of Numbers with N digits which consists of even number of 0's are: "<<count_even(N); return 0; }
Output
If we run the above code it will generate the following output- −
Count of Numbers with N digits which consists of even number of 0's are: 755