Hello Everyone! I was looking for some help with project Euler #20...I have gotten a number in the correct ball park, but it is still wrong. I was curious if someone could take a look at my code and tell me what i could tweak to fix the problem.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
double factorial(double);
double factorial(double x) {
double temp;
if (x <= 1) return 1;
temp = x * factorial(x - 1);
return temp;
}
int main() {
double tmp = factorial(100);
std::vector<int> vec;
std::ostringstream strs;
strs << std::fixed << tmp;
std::string str = strs.str();
for (std::string::size_type i = 0; i < str.size(); ++i) {
vec.push_back(str[i]);
//std::cout << str[i] << std::endl;
}
double out = 0;
for (std::vector<int>::size_type i = 0; i < vec.size(); ++i) {
out += (vec[i] - 48);
//std::cout << vec[i] - 48 << std::endl;
}
std::cout << out << std::endl;
}
This gives me the answer of 681 and i need it to say 640 (if i remember the correct answer). Also any tips for C++ would be nice since I am teaching myself the language.
Also i have it has a double since a double can hold a much larger number than an int or a Long long...the trailing zeros aren't a problem since it shouldn't effect the final answer (if it is crap.)
why are you putting all the digits into a vector instead of just using the string?
You could simply do something like;
1 2 3 4 5 6
std::ostringstream strs;
strs << temp;
for(charconst &digit : strs.str())
sum += digit - '0';
std::cout << sum << std::endl;
I personally used boost instead of double though. With double you are probably not getting the right answer. I just confirmed you are getting the wrong factorial with double.
Also, your "out" should be an int not a double.
A way to get it to work is possibly to get all the digits without the leading zeros.
Hint there is a way to remove 24 of the digits (leading 0's)
ex: anything * 10, * 100, * 1000, * 10000 will only add a 0 to the end.
Thanks for the help giblit! I was using vector because i wasn't thinking...I'm reading accelerated c++ and it was a new tool given to me and my brain kinda derped.
This is what i have now. I'm getting a compile error, but i think it is because i'm missing a file or two, but XCODe isn't picking an error up before compiling. Im just curious i'm on the right track now