C Exercise Example 83
Title:Find the number of odd numbers that can be formed using 0-7.
Program analysis:
This problem is actually a permutation and combination problem. Let this number besun=a1a2a3a4a5a6a7a8,a1-a8 denotes the value of a certain digit of this number. When the last digit of a number is odd, then the number must be odd, no matter what the preceding digits are. If the last digit is even, then the number must be even.
a1-a8 can take the eight digits 0-7, and the leading digit cannot be 0.
Count the number of odd numbers from the case where the number has one digit to the case where it has eight digits:
- 1. When there is only one digit, i.e., the last digit of the number, the number of odd numbers is 4
- 2. When the number has two digits, the number of odd numbers is 4*7=28
- 3. When the number has three digits, the number of odd numbers is: 4*8*7=224
- ...
- 8. When the number has eight digits, the number of odd numbers is: 4*8*8*8*8*8*8*7 (in order from the last digit to the first digit)
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. All rights reserved.
//
#include<stdio.h>
int main(int agrc, char*agrv[])
{
long sum = 4, s = 4;// The initial value of sum is 4, indicating that the number of odd numbers composed of only one digit is 4
int j;
for (j = 2; j <= 8; j++)
{
printf("Number of odd numbers with %d digits: %ld\n", j-1, s);
if (j <= 2)
s *= 7;
else
s *= 8;
sum += s;
}
printf("Number of odd numbers with %d digits: %ld\n", j-1, s);
printf("The total number of odd numbers is: %ld\n", sum);
// system("pause");
return 0;
}
The output of the above example is:
1位数为奇数的个数4 2位数为奇数的个数28 3位数为奇数的个数224 4位数为奇数的个数1792 5位数为奇数的个数14336 6位数为奇数的个数114688 7位数为奇数的个数917504 8位数为奇数的个数7340032 奇数的总个数为:8388608other extensions