C Exercise 83
100 Classic C Language Examples
**Problem:** 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 be sun=a1a2a3a4a5a6a7a8, where a1-a8 represent the value of each digit of the number. When the last digit of a number is odd, the number must be odd, regardless of 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 first digit cannot be 0.
Start counting the number of odd numbers from when the number has one digit up to when it has 8 digits:
- 1. When there is only one digit, which is also 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: 487=224
- ...
- 8. When the number has eight digits, the number of odd numbers is: 4888888*7 (from the last digit to the first in order)
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
int
main
(
int
agrc
,
char
agrv
[
]
)
{
long
sum
=
4
,
s
=
4;
// The initial value of sum is 4, meaning that the number of odd numbers consisting of a single digit is 4
int
j
;
for
(
j
=
2
;
j
<=
8
;
j
++
)
{
printf
(
"
Number of odd %d-digit numbers %ld
\
n
"
,
j
1
,
s
)
;
if
(
j
<=
2
)
s
*=
7
;
else
s
*=
8
;
sum
+=
s
;
}
printf
(
"
Number of odd %d-digit numbers %ld
\
n
"
,
j
1
,
s
)
;
printf
(
"
The total number of odd numbers is: %ld
\
n
"
,
sum
)
;
// system("pause");
return
0
;
}
The above example produces the following output:
1位数为奇数的个数4
2位数为奇数的个数28
3位数为奇数的个数224
4位数为奇数的个数1792
5位数为奇数的个数14336
6位数为奇数的个数114688
7位数为奇数的个数917504
8位数为奇数的个数7340032
奇数的总个数为:8388608