Factors and Factorials
The factorial of a number N (written N!) is defined as the product of all the integers from 1 to N. It is often defined recursively as follows:
Factorials grow very rapidly--5! = 120, 10! = 3,628,800. One way of specifying such large numbers is by specifying the number of times each prime number occurs in it, thus 825 could be specified as (0 1 2 0 1) meaning no twos, 1 three, 2 fives, no sevens and 1 eleven.
Write a program that will read in a number N ( ) and write out its factorial in terms of the numbers of the primes it contains.
Input will consist of a series of lines, each line containing a single integer N. The file will be terminated by a line consisting of a single 0.
Output will consist of a series of blocks of lines, one block for each line of the input. Each block will start with the number N, right justified in a field of width 3, and the characters `!', space, and `='. This will be followed by a list of the number of times each prime number occurs in N!.
These should be right justified in fields of width 3 and each line (except the last of a block, which may be shorter) should contain fifteen numbers. Any lines after the first should be indented. Follow the layout of the example shown below exactly.
5 53 0
5! = 3 1 1 53! = 49 23 12 8 4 4 3 2 2 1 1 1 1 1 1 1
思路:可以先做一张素数表,不用太多,因为题目要求是输入2~100的数,所以我们找出100以内的素数即可。接下来对每次输入都不断的用素数表中每一个数去除它,同一个数要除到不能再除了为止,最后注意打印的格式即可。格式务必注意当输出恰好为15个数的时候是不输出那个换行和那些空格的。
AC代码(0.006s):
#include <stdio.h> int IsPrime(int n) { int i; for (i = 2; i * i <= n; i++) { if (n % i == 0) { return 0; } } return 1; } int main(int argc, const char * argv[]) { int i, count = 0; int prime[100] = {0}; for (i = 2; i < 100; i++) { if (IsPrime(i)) { prime[count++] = i; } } int input, j; while (scanf("%d", &input)) { if (input == 0) { break; } int ans[100] = {0}, maxCur = -1; for (i = 2; i <= input; i++) { int m = i; for (j = 0; j < count; j++) { if (m < prime[j]) { break; } while (m % prime[j] == 0) { ans[j]++; m /= prime[j]; if (j > maxCur) { maxCur = j; } } } } int numCount = 0; printf("%3d! =", input); for (i = 0; i <= maxCur; i++) { printf("%3d", ans[i]); numCount++; if (numCount == 15) { numCount = 0; if (i + 1 <= maxCur) { printf("\n "); } } } printf("\n"); } return 0; }