Something is wrong with code. cant seem to figue out please help.
May 12, 2018 at 5:05pm UTC
Write your question here.
so i wrote this code. you time amount of testcases and then the testcases themselves. program should output factorial of integer represented by testcase. for some reason at the end it keeps adding one number. can anyone explain what is going on?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
#include <bits/stdc++.h>
#include <algorithm>
#include <string>
using namespace std;
int testcase[100], t, num[200], size, x;
int factorial(int n){
if (n>=100)return 0;
else {
num[0]=1;
for (int i=1; i<=n; i++){
size=size+2;
int carry=0;
for (int j=0; j<size; j++){
x=num[j]*i+carry;
if (x>=10) num[j]=x%10;
else num[j]=x;
carry=x/10;
}
}
while (num[size-1]==0)size--;
reverse(num, num+size);
for (int i=0; i<size; i++){
cout<<num[i];
num[i]=0;
}
}
}
int main(){
cin>>t;
for (int j=0; j<t; j++){
cin>>testcase[j];
}
for (int j=0; j<t; j++){
cout<<factorial(testcase[j])<<endl;
}
return 0;
}
/* __ __ _ _ ____ _
| \/ (_) | | | _ \ | |
| \ / |_ ___| |__ ___ | |_) |_ __ __ _ ___| |__
| |\/| | / __| '_ \ / _ \ | _ <| '__/ _` |/ __| '_ \
| | | | \__ \ | | | (_) | | |_) | | | (_| | (__| | | |
|_| |_|_|___/_| |_|\___/ |____/|_| \__,_|\___|_| |_|
*/
May 12, 2018 at 7:32pm UTC
$ grep -n cout factorial.cpp
36: cout<<num[i];
57: cout<<factorial(testcase[j])<<endl;
Factorial is a function that produces its own output. Since its a function it can return a value. Since that value isn't specified, whatever "noise" is returned instead is being printed by cout, after the function itself is printed. Then, the endline.
This fixes the problem:
1 2 3 4 5 6
for (int j=0; j<t; j++){
// cout<<factorial(testcase[j])<<endl;
factorial(testcase[j]);
cout << endl;
}
May 12, 2018 at 8:13pm UTC
Your code can be improved a little:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <iostream>
using namespace std;
void factorial(int n){
char num[500] = {1, 0};
int size = 1;
if (n > 100) {
cout << "overflow\n" ;
return ;
}
for (int i = 2; i <= n; i++) {
int carry = 0;
for (int j = 0; j < size; j++) {
int x = num[j] * i + carry;
num[j] = x % 10;
carry = x / 10;
}
while (carry > 0) {
num[size++] = carry % 10;
carry /= 10;
}
}
for (int i = size; i-- > 0; ) {
cout << char (num[i]+'0' );
num[i] = 0;
}
}
int main(){
int t;
cin >> t;
for (int j = 0; j < t; j++) {
int testcase = 0;
cin >> testcase;
factorial(testcase);
cout << '\n' ;
}
return 0;
}
May 13, 2018 at 7:49am UTC
thanks both replies helped a lot.
Topic archived. No new replies allowed.