首页 > 试题广场 >

求整数的阶乘

[编程题]求整数的阶乘
  • 热度指数:3540 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
求任一正整数的阶乘(注意:是任意正整数)
该正整数不大于1000。


输入描述:
输入一个正整数


输出描述:
输出一个正整数
示例1

输入

3

输出

6
示例2

输入

10

输出

3628800
importjava.math.BigInteger;
importjava.util.Scanner;
 
publicclassMain{
    publicstaticvoidmain(String[] args){
        Scanner sca = newScanner(System.in);
        intn = sca.nextInt();
        intresult=1;
        String s = String.valueOf(result);
        BigInteger answer = newBigInteger(s);
        for(inti=1;i<=n;i++){
            String x=String.valueOf(i);
            BigInteger v = newBigInteger(x);
             
            answer = answer.multiply(v);
        }
        System.out.println(answer);
        sca.close();
    }
     
}
发表于 2019-03-26 16:40:10 回复(0)
import sys

N = int(sys.stdin.readlines()[0])
M = 1
while (N > 0):
    M *= N;
    N -= 1;
print(M)
还是python大法好啊
发表于 2019-11-21 23:28:29 回复(0)
#include <iostream>
#include <string>
using namespace std;

//数据太大无法通过整数数据类型表示,用字符串表示输出
//对于每个字符串从尾部开始进行简单的乘法,进位
void Core(string& res,const int n)
{
    int t = 0;
    for(int i = res.size()-1; i >= 0; i--)
    {
        int tmp = t;
        t = ((res[i] - '0')*n + t) / 10;
        res[i] = (((res[i] - '0')*n + tmp) % 10) + '0';
    }
//若t != 0 即存在进位
    if(t)
    {
        res = to_string(t) + res;
    }
}

int main()
{
    int n;
    cin >> n;
    string res = "1";
    for(int i = 1; i <= n; ++i)
    {
        Core(res,i);
    }
    cout << res;
    return 0;
}


发表于 2019-11-08 10:05:51 回复(0)

#include
const int maxn = 20000+10;
int a[maxn];
int main(){
int n;
while(scanf("%d", &n) == 1){
a[0] = 1;
int digit = 1, temp = 0;
for(int i=2; i<=n; i++){
for(int j=0; j<digit; j++){
a[j] = a[j] * i + temp;
temp = a[j] / 10;
a[j] = a[j] % 10;
}
while(temp != 0){
a[digit++] = temp % 10;
temp /= 10;
}
}
for(int i=digit-1; i>=0; i--){
printf("%d", a[i]);
}
printf("\n");
}
return 0;
}

发表于 2019-03-14 15:30:14 回复(2)
import java.util.*;
import java.math.*;
public class Main{
    static BigInteger func(int n){
        BigInteger res= BigInteger.valueOf(n);
        if(n==1) return new BigInteger("1");
        if(n>1){
            res=res.multiply(func(n-1));
        }
        return res;
    }
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        System.out.println(func(n));
    }
}

发表于 2020-08-25 01:01:55 回复(0)
//采用大数乘法
//数组存储大数
#include<iostream>
(720)#include<string>
using namespace std;

void Figure(int a[],int b)
{
    int h;
    for(int i=0;i<=10000;)
    {
        if(a[i]==0)
            i++;
        else
        {
            h=i;
            break;
        }
    }
    int flag=0;
    for(int j=10000;j>=h-3;j--)
    {
        a[j]=a[j]*b+flag;
        flag=a[j]/10;
        a[j]=a[j]%10;
    }
}

int main()
{
    string s;
    cin>>s;
    int a[10001]={0};
    for(int j=s.size()-1,i=10000;j>=0;j--)
    {
        a[i]=s[j]-'0';
        i--;
    }
    int b=stoi(s.c_str());
    while(b>=3)
    {
        b--;
        Figure(a,b);
    }
    int j=0;
    for(;j<=10000;j++)
    {
        if(a[j]!=0)
            break;
    }
    for(int i=j;i<=10000;i++)
        cout<<a[i];
}

发表于 2020-03-27 11:01:39 回复(0)
#include <bits/stdc++.h>
using namespace std;
string strmul(string s1,string s2){
    string str(s1.size()+s2.size(),'0');
    reverse(s1.begin(),s1.end());
    reverse(s2.begin(),s2.end());
    int k,up;
    for(int i=0;i<s1.size();i++){
        k=i;
        up=0;
        for(int j=0;j<s2.size();j++,k++){
            int t=(s1[i]-'0')*(s2[j]-'0')+up+str[k]-'0';
            up=t/10;
            str[k]=t%10+'0';
        }
        str[k]=up+'0';
    }
    k=str.size()-1;
    while(str[k]=='0')
        str.pop_back();
    reverse(str.begin(),str.end());
    return str;
}
int main(){
    int n;
    cin>>n;
    string ans="1";
    for(int i=1;i<=n;i++)
        ans=strmul(ans,to_string(i));
    cout<<ans;
    return 0;
}

发表于 2019-11-14 17:03:50 回复(0)
#include <bits/stdc++.h>
#define M 3000
using namespace std;

int main(){
    int n;
    int a[M];
    while(cin>>n){
        int t = 0;
        memset(a, 0, sizeof(a));
        a[0] = 1;
        for(int i=1;i<=n;i++){
            int c = 0;
            for(int j=0;j<=t;j++){
                int r = (a[j]*i+c)/10;
                a[j] = (a[j]*i+c)%10;
                c = r;
            }
            while(c!=0){
                a[++t] = c%10;
                c /= 10;
            }
        }
        for(int i=t;i>=0;i--)
            cout<<a[i];
        cout<<endl;
    }
    return 0;
}

发表于 2019-08-07 15:22:22 回复(0)
""""
应该考察大数乘法,python真的犯规
"""

if __name__ == "__main__":
    n = int(input())
    ans = 1
    for i in range(1, n + 1):
        ans *= i
    print(ans)

发表于 2019-07-15 19:03:49 回复(0)
n=int(input())
ans=1;
for i in range(1,n+1,1):
    ans*=i
print(ans)

发表于 2021-03-31 20:59:59 回复(0)
p = 1
for i in range(1,1 + int(input())):
    p *= i
print(p)
感觉python好短啊,除了怕超时超限就无敌了
发表于 2020-03-14 11:56:26 回复(0)
import java.util.Scanner;
import java.math.BigInteger;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        BigInteger n = sc.nextBigInteger();
        //System.out.println(n);
        System.out.println(fac(n));  //不能对Main中的非静态方法进行静态引用
        sc.close();
    }
    public static BigInteger fac(BigInteger a){
        if (a == BigInteger.valueOf(1)){
            return BigInteger.valueOf(1);  
        }else{
            return a.multiply(fac(a.subtract(BigInteger.valueOf(1))));
        }
    }
}
发表于 2020-01-23 13:17:37 回复(0)
感觉大数乘法代码不是很简洁,不过好歹通过了
#include<stdio.h>

#define LEN 10000

void minus(int a[],int n);

int main()
{
    int n;
    scanf("%d",&n);
    int a[LEN] = {1};
    for(int i = 2;i <= n;++i){
        minus(a,i);
    }
    int j;
    for(j = LEN - 1;a[j] == 0;--j);
    for(;j >= 0;--j){
      printf("%d",a[j]);
    }
    
    return 0;
}

void minus(int a[],int n)
{
    for(int i = 0;i < LEN;++i){
      a[i] *= n;
    }
    for(int j = 0;j < LEN - 1;++j){
      if(a[j] >= 10){
        int t = a[j] / 10;
        a[j] %= 10;
        a[j + 1] += t;
      }
    }
}


发表于 2019-10-04 02:01:10 回复(0)
class Program
    {
        static void Main(string[] args)
        {
            string line;
            int n;
            List<int> list;
            while ((line = Console.ReadLine()) != null)
            {
                n = int.Parse(line);
                list = new List<int>();
                list.Add(n);
                int carry = 0;
                while (n > 1)
                {
                    n--;
                    for (int i = 0; i < list.Count; i++)
                    {
                        list[i] = list[i] * n + carry;
                        carry = list[i] / 10;
                        list[i] = list[i] % 10;
                    }
                    while (carry != 0)
                    {
                        list.Add(carry % 10);
                        carry /= 10;
                    }
                }
                for (int i = list.Count-1; i >= 0 ; i--)
                {
                    Console.Write(list[i]);
                }
                Console.WriteLine();
            }
        }
    }
发表于 2019-09-10 18:27:28 回复(0)
n=int(input())
deffuu(n):   
    ifn==0:
        return0
    elifn==1:
        return1
    else:
        return(fuu(n-1)*n)
print(fuu(n))



有人帮我看下吗,只通过了86%
发表于 2019-08-19 15:18:46 回复(0)
import java.math.BigInteger;
import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        System.out.println(calculate(a));
    }
    public static BigInteger calculate(int a) {
        BigInteger result = BigInteger.valueOf(1);
        for (int i = 1; i < a + 1; i++) {
            BigInteger b = BigInteger.valueOf(i);
            result = result.multiply(b);
        }
        return result;
    }
}
占用内存12708k,时间:90-97ms
发表于 2019-07-02 11:28:14 回复(0)
#include<iostream>
#include<stdlib.h>
using namespace std;
const int MAXN = 3000;
int main()
{
    int n;
    while(cin>>n)
    {
        int ans[MAXN] = {0};
        ans[0] = 1;
        for(int i=2; i<=n; i++)
        {
            int c = 0;//保存进位
            for(int j=0; j<MAXN; j++)  //每一步循环算出来的都是i的阶乘
            {
                int temp = ans[j]*i + c;//每个数都要与i相乘
                ans[j] = temp%10;
                c = temp/10;
            }
        }
        int i;
        for(i=MAXN-1; i>=0; i--)
            if(ans[i])
                break;
        for(int j=i; j>=0; j--)
            cout<<ans[j];
        cout<<endl;
    }
    return0;
}
编辑于 2019-06-03 16:06:06 回复(0)
import java.util.*;

public class Main {     public static void main(String args[]) {              Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        System.out.println(new Main().factorial(n));          }

    //这个题是大数的阶乘,如果使用一般类型是不行的,这里我们先实现相乘
    public String MultiplicationStr (String first, String second) {
        //受限字符串必须都是数字[0-9]+,并且至少出现一次
        String regEx = "^[0-9]+$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(first);
        Matcher matcher1 = pattern.matcher(second);
        if(!matcher.matches() || !matcher1.matches()) {
            return "-1";
        }

        //数据校验通过,然后我们开始进行相乘操作
        String result = "0";
        int b10 = 0;
        //我们取最长的那个
        long upNum = 0;
        for(int i = first.length() - 1; i >= 0; --i) {
            //遍历这个字符
            long temp1 = Long.valueOf(first.charAt(i) + "");
            String tmpResultStr = "";
            for(int j = second.length() - 1; j >= 0; --j) {
                long temp2 = Long.valueOf(second.charAt(j) + "");

                //这里要考虑进位
                long tempResult = temp1 * temp2 + upNum;

                upNum = tempResult / 10;
                long curNum = tempResult % 10;

                tmpResultStr = curNum + tmpResultStr;
            }

            //添加进位数
            if(upNum > 0) {
                tmpResultStr = upNum + tmpResultStr;
                upNum = 0;
            }


            //添加10的倍数
            for(int b = 0; b < b10; ++b) {
                tmpResultStr += "0";
            }
            ++b10;
            if(tmpResultStr.equals("")) {
                tmpResultStr = "0";
            }
            result = this.add(result, tmpResultStr);

        }

        //我们最后还要把进位的加上,这里考虑
//        if(upNum > 0) {
//            result = upNum + result;
//        }
        return result;

    }
    
    /**
     *
     * @program: y2019.m03.d22.FactorialNum
     * @description: 字符相加
     * @auther: xiaof
     * @date: 2019/3/22 20:14
     */
    public String add(String num1, String num2) {
        String regEx = "^[0-9]+$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(num1);
        Matcher matcher1 = pattern.matcher(num2);
        if(!matcher.matches() || !matcher1.matches()) {
            return "0";
        }
        //相加
        int i = num1.length() - 1, j = num2.length() - 1, index = num1.length() > num2.length() ? num1.length() : num2.length();
        int upNum = 0;
        String result = "";
        for(; index > 0; --i,--j, --index) {
            //获取当前位阶的数据
            int n1 = 0;
            int n2 = 0;

            if(i >= 0) {
                n1 = Integer.valueOf(num1.charAt(i) + "");
            }

            if(j >= 0) {
                n2 = Integer.valueOf(num2.charAt(j) + "");
            }

            int tempSum = n1 + n2 + upNum;

            upNum = tempSum / 10;
            int curNum = tempSum % 10;

            result = String.valueOf(curNum) + result;
        }

        //最后计算剩余的长度值
        if(upNum > 0) {
            result = upNum + result;
        }

        return result;

    }

    public String factorial (int n) {

        if(n == 0) {
            return "0";
        }
        if(n == 1) {
            return "1";
        }
        String result = "1";
        for(int i = 2; i <= n; ++i) {
            result = this.MultiplicationStr(result, i + "");
        }

        return result;
    }


}
为什么我这个会超时???

发表于 2019-03-22 23:30:56 回复(0)
import java.util.*;
public  class Main{
    public static void main(String[]args){
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        System.out.println(new Main().getJieChen(n));
 
    }
public String getJieChen(int num){
        String result = "1";
        for(int i=2;i<=num;i++){
            result = strChar(result,i+"");
        }

        return result;
    }

    public String strChar(String str,String str1){
        StringBuilder result = new StringBuilder();
        for(int i=str1.length()-1;i>=0;i--){
            int carry = 0;
            StringBuilder sb = new StringBuilder();
            for(int k = i;k<str1.length()-1;k++)
                sb.append(0);
            for(int j=str.length()-1;j>=0;j--){
                int n = (str1.charAt(i)-48)*(str.charAt(j)-48);
                sb.append((n+carry)%10);
                carry = (n+carry)/10;
            }
            if(carry>0)
                sb.append(carry);
            if(i==str1.length()-1)
                result.append(sb);
            else
                result = addTwoBuilder(result,sb);

        }
        return result.reverse().toString();
    }

    public StringBuilder addTwoBuilder(StringBuilder sb1,StringBuilder sb2){
        int carry = 0;
        int i = 0;
        for(;i<sb1.length()&&i<sb2.length();i++){
            int n = sb1.charAt(i)+sb2.charAt(i)-96;
            sb1.setCharAt(i,(char)((n+carry)%10+48));
            carry = (n+carry)/10;
        }
        StringBuilder s = sb1;
        if(sb2.length()>i){
            for(int i1=i;i1<sb2.length();i1++)
                s.append(sb2.charAt(i1));
        }
        if (carry > 0) {
            for (int j = i; j < s.length(); j++) {
                int n = sb1.charAt(j) - 48 +carry;
                if(j<sb1.length()){
                    sb1.setCharAt(j,(char)(n%10+48));
                }else{
                    sb1.append((char)(n%10+48));
                }
                carry = n/10;
            }
        }
         if(carry>0)
            sb1.append(carry);
        return sb1;


    }
 
}

发表于 2019-03-18 15:24:24 回复(1)
直接考虑大整数相乘,不解释,上代码:
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define maxsize 100
typedef long long ll;
using namespace std;
string getstring(int x) {
    string result;
    while(x) {
        result+=x%10+'0';
        x/=10;
    }
    reverse(result.begin(),result.end());
    return result;
}
string mulstring(string des,string sou) {
    string result;
    int index=0,carry=0,i,j;
    int des_len=des.size();
    int sou_len=sou.size();
    int r[des_len+sou_len+1];
    memset(r,0,(des_len+sou_len)*sizeof(int));
    reverse(des.begin(),des.end());
    reverse(sou.begin(),sou.end());
    for(i=0; i<des_len; i++)
        for(j=0; j<sou_len; j++)
            r[i+j]+=(des[i]-'0')*(sou[j]-'0');
    while(index<des_len+sou_len) {
        int t=r[index];
        r[index]=(t+carry)%10;
        carry=(t+carry)/10;
        index++;
    }
    while(carry) {
        r[index++]=carry%10;
        carry/=10;
    }
    for(i=index-1; i>=0; i--) if(r[i]) break;
    for(j=i; j>=0; j--) result+=r[j]+'0';
    return result;
}
int main(int argc, char const *argv[]) {
#ifdef ONLINE_JUDGE
#else
    freopen("input.txt","r",stdin);
#endif
    int n;
    while(cin>>n&&!cin.eof()) {
        string str="1";
        if(n==1) {
            cout<<str<<endl;
            break;
        }
        for(int i=1; i<=n; i++) str=mulstring(str,getstring(i));
        cout<<str<<endl;
    }
    return 0;
}

发表于 2019-03-15 11:38:07 回复(1)