• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 11:45
CEST 17:45
KST 00:45
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL21] Ro16 Preview Pt2: All Star10Team Liquid Map Contest #22 - The Finalists16[ASL21] Ro16 Preview Pt1: Fresh Flow9[ASL21] Ro24 Preview Pt2: News Flash10[ASL21] Ro24 Preview Pt1: New Chaos0
Community News
2026 GSL Season 1 Qualifiers19Maestros of the Game 2 announced92026 GSL Tour plans announced15Weekly Cups (April 6-12): herO doubles, "Villains" prevail1MaNa leaves Team Liquid25
StarCraft 2
General
MaNa leaves Team Liquid Maestros of the Game 2 announced 2026 GSL Tour plans announced Team Liquid Map Contest #22 - The Finalists Blizzard Classic Cup @ BlizzCon 2026 - $100k prize pool
Tourneys
2026 GSL Season 1 Qualifiers INu's Battles#14 <BO.9 2Matches> Sparkling Tuna Cup - Weekly Open Tournament GSL CK: More events planned pending crowdfunding RSL Revival: Season 5 - Qualifiers and Main Event
Strategy
Custom Maps
[D]RTS in all its shapes and glory <3 [A] Nemrods 1/4 players [M] (2) Frigid Storage
External Content
Mutation # 522 Flip My Base The PondCast: SC2 News & Results Mutation # 521 Memorable Boss Mutation # 520 Moving Fees
Brood War
General
BGH Auto Balance -> http://bghmmr.eu/ Data needed ASL21 General Discussion FlaSh: This Will Be My Final ASL【ASL S21 Ro.16】 BW General Discussion
Tourneys
Escore Tournament StarCraft Season 2 [Megathread] Daily Proleagues [ASL21] Ro16 Group C [ASL21] Ro16 Group D
Strategy
Simple Questions, Simple Answers What's the deal with APM & what's its true value Any training maps people recommend? Fighting Spirit mining rates
Other Games
General Games
Nintendo Switch Thread Dawn of War IV Diablo IV Total Annihilation Server - TAForever Starcraft Tabletop Miniature Game
Dota 2
The Story of Wings Gaming
League of Legends
G2 just beat GenG in First stand
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
Vanilla Mini Mafia Mafia Game Mode Feedback/Ideas TL Mafia Community Thread Five o'clock TL Mafia
Community
General
US Politics Mega-thread Canadian Politics Mega-thread Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread YouTube Thread
Fan Clubs
The IdrA Fan Club
Media & Entertainment
[Manga] One Piece Anime Discussion Thread [Req][Books] Good Fantasy/SciFi books Movie Discussion!
Sports
2024 - 2026 Football Thread Formula 1 Discussion McBoner: A hockey love story Cricket [SPORT]
World Cup 2022
Tech Support
Strange computer issues (software) [G] How to Block Livestream Ads
TL Community
The Automated Ban List
Blogs
Sexual Health Of Gamers
TrAiDoS
lurker extra damage testi…
StaticNine
Broowar part 2
qwaykee
Funny Nicknames
LUCKY_NOOB
Iranian anarchists: organize…
XenOsky
Customize Sidebar...

Website Feedback

Closed Threads



Active: 2216 users

C++ Factorial Function - Page 2

Blogs > ChristianS
Post a Reply
Prev 1 2 All
LegalLord
Profile Blog Joined April 2013
United States13779 Posts
August 13 2017 18:49 GMT
#21
I don't really like C++ Primer. No specific feedback, I just always felt whenever I was reading it that it didn't really go about teaching things the right way. CS books are generally all available online for free though, so Google the book and give it a read-through before buying if that's you cup of tea.

"Advanced" beginner is basically that you've done some work before and that you'd be fairly quick at picking new things up. The Stroustrup book makes you a better programmer, especially in C++, but it will absolutely make you have to work pretty hard for it. I will say that I definitely feel that I understood C++ on a much deeper level after I got through that book though. Ultimately it's only a first step, because there are further fundamentals of software that you simply don't get from an introductory course, but it's enough to put you on a solid foundation for moving forward. Self-study always comes with the downside that it's easy to get off course, learn something poorly, and never really be able to move on because you just get lost in the more advanced material.
History will sooner or later sweep the European Union away without mercy.
ChristianS
Profile Blog Joined March 2011
United States3304 Posts
August 13 2017 19:07 GMT
#22
Oh wow, that is cheap. Ordered.

Yeah, I bet there's a lot of "self-taught programmers" out there that make CS professionals roll their eyes, and I guess I'm joining their ranks. I'm hoping to try to avoid too many bad habits by trying to be fairly careful in the early chapters before jumping to the other stuff. Pointers seem like a big one that make it very easy to get yourself into trouble – there's all kinds of mistakes I can make with them that the compiler won't tell me about, and a lot of them will still give the right output in most cases so I won't realize I screwed up.

Maybe I'll keep writing blogs like this one so TL coders can keep me on track (if they're willing).
"Never attribute to malice that which is adequately explained by stupidity." -Robert J. Hanlon
LegalLord
Profile Blog Joined April 2013
United States13779 Posts
August 13 2017 20:14 GMT
#23
CS professionals tend to have huge egos; there is a lot of things that will make them roll their eyes .

In all seriousness: yeah, there's definitely a lot of people here that are fairly experienced in software. For me, it's a secondary, albeit critical, part of my job (I'm a rocket engineer first and foremost), but there's definitely a lot of people around here who are very skilled in software and do it as their primary job. Video games and software development tend to go hand-in-hand for reasons that are both obvious and not.

As for pointers: a C coder would very much have a tendency to overuse those. I'd say the best way to get a handle on how to best use them is to take some form of algorithms course once you feel you have the basics of C++ down. Quora has a decent list of courses that are available; pick one that is C++ based (because C++ is the best language for that kind of study).
History will sooner or later sweep the European Union away without mercy.
beg
Profile Blog Joined May 2010
991 Posts
Last Edited: 2017-08-13 22:05:35
August 13 2017 21:53 GMT
#24
On August 14 2017 03:49 LegalLord wrote:
I don't really like C++ Primer. No specific feedback, I just always felt whenever I was reading it that it didn't really go about teaching things the right way. CS books are generally all available online for free though, so Google the book and give it a read-through before buying if that's you cup of tea.

"Advanced" beginner is basically that you've done some work before and that you'd be fairly quick at picking new things up. The Stroustrup book makes you a better programmer, especially in C++, but it will absolutely make you have to work pretty hard for it. I will say that I definitely feel that I understood C++ on a much deeper level after I got through that book though. Ultimately it's only a first step, because there are further fundamentals of software that you simply don't get from an introductory course, but it's enough to put you on a solid foundation for moving forward. Self-study always comes with the downside that it's easy to get off course, learn something poorly, and never really be able to move on because you just get lost in the more advanced material.

EDIT: Damnit, you guys were talking about a book called "C++ Primer Plus". I noticed too late. That is a very different book from the legendary "C++ Primer".

My original post:
I love C++ Primer! It teaches the whole language in a no bullshit approach. Very academic and to the point. But also very thorough with all the details of C++. Definitely not an easy book. I already had experience with C when I read it. It's a challenge for a complete beginner.

I totally agree with your advice to check out various books by googling. That's what I did too. My choice was C++ Primer
bo1b
Profile Blog Joined August 2012
Australia12814 Posts
Last Edited: 2017-08-15 03:50:11
August 15 2017 03:47 GMT
#25
C++ primer 5th edition is by far the best book for learning c++ from scratch in my opinion, primer plus has (had maybe?) quite a few flaws in it, while primer went in and taught you proper practices very quickly.

For what it's worth, using pointers quite a lot of the time is unnecessary over engineering, but if you're teaching yourself at home I'd try and put them in just about everything until you are super comfortable using them, as there are times when you will have to use them, and they will be complicated as hell otherwise. This includes const pointers as well.
LegalLord
Profile Blog Joined April 2013
United States13779 Posts
Last Edited: 2017-08-15 04:44:44
August 15 2017 04:36 GMT
#26
I looked back over the book and basically confirmed my criticisms. Primer suffers from a bad case of being overly pedantic and missing the forest for the trees in terms of a book meant to teach the younglings how to code. A bit too basic to be a good reference, but far too convoluted to be a good starter book.

I saw one example there that instantly bugged me, in like chapter 1 or 2. It was something like "well the proper way is return x+4; because its faster but if you aren't comfortable with that to int y = x+4; return y; but that's bad." Lots of little tidbit micro-optimizations that frankly don't add anything to the learning experience, but that kind of just overload you with minutia that is best saved for when you can actually understand the concepts behind certain coding choices - at which point it becomes less of an artificial rule and more of an automatically ingrained concept.

Not that it's a bad book by any means - it's still a pretty solid resource - but I wouldn't recommend trying to learn from it, at least not without further resources. It can lead to making a simple exercise like a factorial turn into a convoluted pile o' crap. Of course, it's always nice to have multiple resources to reference because books are seldom universally perfect at doing everything.
History will sooner or later sweep the European Union away without mercy.
bo1b
Profile Blog Joined August 2012
Australia12814 Posts
August 15 2017 04:44 GMT
#27
I don't recall any such instance, are you certain that wasn't primer plus?
LegalLord
Profile Blog Joined April 2013
United States13779 Posts
August 15 2017 04:46 GMT
#28
On August 15 2017 13:44 bo1b wrote:
I don't recall any such instance, are you certain that wasn't primer plus?

Nope, Primer 5th as referenced above.

I will say that I do appreciate its focus on style and "doing things right" - but frankly that is best learned incrementally rather than through up-front where it's going to lead to coding paralysis and still kind of bad results.
History will sooner or later sweep the European Union away without mercy.
ChristianS
Profile Blog Joined March 2011
United States3304 Posts
August 15 2017 05:27 GMT
#29
On August 15 2017 13:36 LegalLord wrote:
I looked back over the book and basically confirmed my criticisms. Primer suffers from a bad case of being overly pedantic and missing the forest for the trees in terms of a book meant to teach the younglings how to code. A bit too basic to be a good reference, but far too convoluted to be a good starter book.

I saw one example there that instantly bugged me, in like chapter 1 or 2. It was something like "well the proper way is return x+4; because its faster but if you aren't comfortable with that to int y = x+4; return y; but that's bad." Lots of little tidbit micro-optimizations that frankly don't add anything to the learning experience, but that kind of just overload you with minutia that is best saved for when you can actually understand the concepts behind certain coding choices - at which point it becomes less of an artificial rule and more of an automatically ingrained concept.

Not that it's a bad book by any means - it's still a pretty solid resource - but I wouldn't recommend trying to learn from it, at least not without further resources. It can lead to making a simple exercise like a factorial turn into a convoluted pile o' crap. Of course, it's always nice to have multiple resources to reference because books are seldom universally perfect at doing everything.
Harsh! I thought I was pretty clear that I thought the simple solution was the best, and I was just trying to think about these other ways to do it as an exercise in thinking about the consequences of using these more complicated mechanisms.

Speaking of needlessly overcomplicating the factorial function, what if I had the function return a union which can hold either a long long or a long double? Then if the answer fits in a long long I return that, otherwise I return the next-best long double. Too hacky? Convoluted pile of crap?
"Never attribute to malice that which is adequately explained by stupidity." -Robert J. Hanlon
LegalLord
Profile Blog Joined April 2013
United States13779 Posts
August 15 2017 05:30 GMT
#30
Don't use unions unless you have a good reason to. Read this for some commentary about it.
History will sooner or later sweep the European Union away without mercy.
ChristianS
Profile Blog Joined March 2011
United States3304 Posts
August 15 2017 05:55 GMT
#31
Oh I think I misunderstood what would happen. I thought I could decide in the function whether to return a long long or long double, but I guess returning a union would be like returning a struct, except if I tried to access the wrong member it would break. What I wanted was something that could intelligently decide which to return based on whether I would overload the long long or not.

Oh well. I promise I'll stop trying to make my factorial function more complicated and just move on to learning other stuff
"Never attribute to malice that which is adequately explained by stupidity." -Robert J. Hanlon
bo1b
Profile Blog Joined August 2012
Australia12814 Posts
August 15 2017 06:24 GMT
#32
Ok fair enough, I don't recall it but it was a while ago.
TanGeng
Profile Blog Joined January 2009
Sanya12364 Posts
August 15 2017 20:09 GMT
#33
So is this exercise going to have an arbitrary length number? Are we thinking like 100! ?

With factorials you're probably doing counting, Which means doing full precision integer math. We want long long for such a calculation, and with large factorials, we go Beyond long long easily. C++ Has exercises with big nums. See http://www.cplusplus.com/forum/lounge/32041/

The declaration might look like:
bigNum* factorial(int);


This makes your factorial code allocation of bigNum. And there is no need to have factorials go Beyond int. The values become too big. The computation is too slow.

Concern for structure passing is an optimization with consideration with How your code translates into Machine code. At this Point, you also WanT to look at other optimizations. If you are going to call this function over and over again, you WanT to memoize and store results. Hash or an array for this memoization can work. Depending on how you do it, you may WanT to convert to:

const bigNum* factorial(int);


RIP capitalization. I pressed the TLPD button.

Moderator我们是个踏实的赞助商模式俱乐部
LegalLord
Profile Blog Joined April 2013
United States13779 Posts
Last Edited: 2017-08-15 20:18:55
August 15 2017 20:15 GMT
#34
If you want bignums, my personal favorite (for C++) is ttmath. It's not arbitrary precision like most (you define a precision at compile-time) but it's easy to use and it's the most performant I've ever used. For a task quite similar to factorials (the Gamma function) I also had issues with overflow and ttmath took care of that problem like a charm, with 0.1% of the trouble of most of the solutions I have seen.
History will sooner or later sweep the European Union away without mercy.
TanGeng
Profile Blog Joined January 2009
Sanya12364 Posts
August 15 2017 20:35 GMT
#35
On August 16 2017 05:15 LegalLord wrote:
If you want bignums, my personal favorite (for C++) is ttmath. It's not arbitrary precision like most (you define a precision at compile-time) but it's easy to use and it's the most performant I've ever used. For a task quite similar to factorials (the Gamma function) I also had issues with overflow and ttmath took care of that problem like a charm, with 0.1% of the trouble of most of the solutions I have seen.


ttmath is one of the best open source libraries you can use in C++ for bignums.

For storage sizes:
double itself is 10 bits of exponents and can compute 171 factorials. If you need factorials and care about runtime performance, you might just precompute at compile time and have an array.

long double with GCC is 80-bit precision with 15 bits of exponents. That's a bit more than 3000 distinct answers. Getting a full precision for factorials greater than 3000 is sizeable. Something to think about.

With bignums, you can really get up there with the precision and size of answers. Consider your needs before using and implementing.
Moderator我们是个踏实的赞助商模式俱乐部
Prev 1 2 All
Please log in or register to reply.
Live Events Refresh
uThermal 2v2 Circuit
15:00
Season 2 - Bonus Cup 8
uThermal277
mouzHeroMarine192
RotterdaM159
IndyStarCraft 127
LiquipediaDiscussion
Ladder Legends
15:00
Valedictorian Cup #1
Bunny vs GgMaChine
ByuN vs Percival
MaxPax vs Krystianer
Solar vs Cham
SteadfastSC55
Liquipedia
PSISTORM Gaming Misc
14:55
FSL s10 Code S FINALS
Freeedom20
Liquipedia
WardiTV Map Contest Tou…
11:00
Playoffs Day 3
MaxPax vs Percival
herO vs Clem
WardiTV1413
IntoTheiNu 321
Ryung 179
Rex131
EnkiAlexander 50
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
uThermal 277
mouzHeroMarine 192
Ryung 179
RotterdaM 159
SortOf 156
Rex 131
IndyStarCraft 127
SteadfastSC 55
ProTech29
BRAT_OK 24
Vindicta 18
StarCraft: Brood War
Horang2 13060
EffOrt 1195
Stork 532
actioN 346
ggaemo 331
firebathero 238
Hyun 170
Sharp 108
Dewaltoss 87
Pusan 73
[ Show more ]
soO 58
ToSsGirL 54
Barracks 51
Free 47
Noble 27
Sexy 27
Rock 25
yabsab 16
GoRush 15
IntoTheRainbow 14
Terrorterran 7
Dota 2
Gorgc6533
qojqva1376
Counter-Strike
byalli1565
fl0m1528
Heroes of the Storm
Khaldor703
Liquid`Hasu353
MindelVK10
Other Games
singsing2399
B2W.Neo1095
FrodaN687
QueenE324
XBOCT273
DeMusliM261
Sick259
Lowko248
mouzStarbuck162
KnowMe65
Organizations
Dota 2
PGL Dota 2 - Main Stream19658
StarCraft: Brood War
Kim Chul Min (afreeca) 11
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
[ Show 18 non-featured ]
StarCraft 2
• LUISG 16
• Dystopia_ 3
• sooper7s
• AfreecaTV YouTube
• Migwel
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
StarCraft: Brood War
• FirePhoenix2
• Michael_bg 1
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
League of Legends
• Jankos4886
• TFBlade1293
Other Games
• WagamamaTV359
• Shiphtur205
Upcoming Events
BSL
3h 15m
Sparkling Tuna Cup
18h 15m
WardiTV Map Contest Tou…
19h 15m
Ladder Legends
23h 15m
BSL
1d 3h
CranKy Ducklings
1d 8h
Replay Cast
1d 17h
Wardi Open
1d 18h
Afreeca Starleague
1d 18h
Soma vs hero
Monday Night Weeklies
2 days
[ Show More ]
Replay Cast
2 days
Replay Cast
2 days
Afreeca Starleague
2 days
Leta vs YSC
Replay Cast
4 days
The PondCast
4 days
KCM Race Survival
4 days
Replay Cast
5 days
Replay Cast
5 days
Escore
5 days
Replay Cast
6 days
Replay Cast
6 days
Liquipedia Results

Completed

Escore Tournament S2: W4
RSL Revival: Season 4
NationLESS Cup

Ongoing

BSL Season 22
ASL Season 21
CSL 2026 SPRING (S20)
IPSL Spring 2026
KCM Race Survival 2026 Season 2
StarCraft2 Community Team League 2026 Spring
WardiTV TLMC #16
Nations Cup 2026
IEM Rio 2026
PGL Bucharest 2026
Stake Ranked Episode 1
BLAST Open Spring 2026
ESL Pro League S23 Finals
ESL Pro League S23 Stage 1&2
PGL Cluj-Napoca 2026

Upcoming

Escore Tournament S2: W5
Acropolis #4
BSL 22 Non-Korean Championship
CSLAN 4
Kung Fu Cup 2026 Grand Finals
HSC XXIX
uThermal 2v2 2026 Main Event
Maestros of the Game 2
2026 GSL S2
RSL Revival: Season 5
2026 GSL S1
XSE Pro League 2026
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
IEM Atlanta 2026
Asian Champions League 2026
PGL Astana 2026
BLAST Rivals Spring 2026
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2026 TLnet. All Rights Reserved.