题目:挑战类型表示的极限——大数存储问题。编程计算并输出1~40之间的所有数的阶乘。
这道题就很简单了,直接c++的vector数组就能解决,或者也可以用java的Arraylist方法很多,主要给数字转化成数组。
import java.util.ArrayList;
public class FactorialCalculator {
public static void main(String[] args) {
for (int i = 1; i <= 40; i++) {
System.out.print(i + "! = ");
printFactorial(factorial(i));
}
}
public static ArrayList<Integer> factorial(int n) {
ArrayList<Integer> result = new ArrayList<>();
result.add(1);
for (int i = 2; i <= n; i++) {
multiply(i, result);
}
return result;
}
private static void multiply(int x, ArrayList<Integer> result) {
int carry = 0;
for (int i = 0; i < result.size(); i++) {
int prod = result.get(i) * x + carry;
result.set(i, prod % 10);
carry = prod / 10;
}
while (carry != 0) {
result.add(carry % 10);
carry /= 10;
}
}
private static void printFactorial(ArrayList<Integer> result) {
for (int i = result.size() - 1; i >= 0; i--) {
System.out.print(result.get(i));
}
System.out.println();
}
}
下面是用c++ vector数组解决这道题
#include <iostream>
#include <vector>
void multiply(int x, std::vector<int>& result) {
int carry = 0;
for (size_t i = 0; i < result.size(); i++) {
int prod = result[i] * x + carry;
result[i] = prod % 10;
carry = prod / 10;
}
while (carry != 0) {
result.push_back(carry % 10);
carry /= 10;
}
}
void printFactorial(const std::vector<int>& result) {
for (auto it = result.rbegin(); it != result.rend(); ++it) {
std::cout << *it;
}
std::cout << std::endl;
}
void factorial(int n) {
std::vector<int> result(1, 1);
for (int i = 2; i <= n; i++) {
multiply(i, result);
}
printFactorial(result);
}
int main() {
for (int i = 1; i <= 40; i++) {
std::cout << i << "! = ";
factorial(i);
}
return 0;
}