Very large numbers in C++ for competitive programming [duplicate] - c++

This question already has an answer here:
Which is a good C++ BigInteger class for programming contests?
(1 answer)
Closed 7 years ago.
I would like to know how to use very large numbers (being accurate 10^100 in C++) for competitive programming. I know libraries like GMP exist but they can't be used sites like SPOJ or CodeChef.
I have used strings, however it takes lot of time to implement it. Now I would like to know what efficient methods do other programmers use and resources to learn those methods. Thanks!

I would like to know what efficient methods other programmers use
Most of the time you can't use any third-party libraries when submitting your solutions to online judge systems like SPOJ or at contests (however some contests need only .out files, so it doesn't matter how you get them).
Since you cannot use anything external, competitive programmers write their BigNum classes on their own. It is not really so hard using dynamic arrays or data structures like std::string in C++.
How to?
Practice is your best friend when you are trying to beat and solve online judge/contest problems.
Paper, pencil, your mind, nothing else is required to find out how to implement your BigNum class.
Consider how you can read/write big numbers as std::string, then go one level further and try to add/remove leading-zeros, count a sum of two big numbers... and then, further things will be easier.

Related

Vectors vs Array in C++ [duplicate]

This question already has answers here:
Using arrays or std::vectors in C++, what's the performance gap?
(21 answers)
Closed 3 years ago.
I am working on a Project in which the I am using vectors since the size of array is unknown initially. Does using arrays instead of vectors reduce the run time of code?If Yes, Then How can i initialize/declare the array of unknown size i.e. Size of array is variable(based on input)? "OR" Is it better to use vectors only?
Note :- I want to know Which better reduces the Execution time of Program.
In programming as in life there is no free meal... Keep that in mind all the time. If you want nice and convenient features you have to pay a price.
std::vector will add some complexity to your code you don't see. Adding items to your std::vector does more, then just writing a value. It may allocate new memory and copy the old values to it. And several more things you won't really see.
Switching to std::array won't give you the boost you might looking for. It is a bit simpler then std::vector. It is the way to got, when you are looking for an supplement of an plain c array. But still, it will add complexity too.
So my advice is and you will find similar once in good books. Try to optimize your code on algorithm base and not on the implementation. There is much more potential in possible flawed algorithms or there may be much better once. The implementation won't give you the ground braking boost.

Is it feasible to have an algorithm in C++ which calls a Fortran program for the heavily computation parts?

I am developing an algorithm that has a large numerical computation part. My project supervisor recommended me to use Fortran because of this and so for the last weeks I've been work on it (so far so good). It would be a new version of an algorithm of his, which is basically a lot of numerical computing.
Mine, however, would have more "logic" to it. Without going into much detail, the brute force approach is done using just fortran because it's just 95% of reading from a file and doing the operations. However, the aim of the project is to provide an efficient algorithm to do this, I had been thinking about methods and wanted to start with a Greedy approach (something like Hill Climbing) and that got me thinking that for this part in particular, maybe it would be better to write the algorithm in C++ instead of Fortran.
So basically, how hard do you think it would be to develop the algorithm "logic" in C++ and then call Fortran whenever the bulk of the numerical computation has to be performed. Would it be worth it? Or should I just stick with one of the two languages?
Sorry if it is a very ignorant question but I can't get an idea of whether writing an algorithm such as Hill Climbing would be more difficult if done with Fortran instead of C++ and the benefits of Fortran in this case would be worth it.
Thanks for your time and have a nice day!

c++ combine hash functions using std::bitset

I recently came across a blog https://worldengineer.me/2015/02/08/combining-container-hashes-with-c14-metaprogramming-cure-for-insomnia-1729/
Where the author combines two hashes by reducing them to their std::bitset representation and concatenating the bitsets and finding the hash of the combined bitset.
Granted that probably the motive of the article was to introduce c++ 14 features, i was wondering how good this approach is compared to say, the boost hash_combine function purely on the basis of collision resistance?
EDIT:
By good i mean how does it fare in avoiding collisions compared to the boost libraries' hash_combine method? And performance wise is it a good option, though i don't think the above approach should take much longer than the hash_combine method.
I am not doing any serious development with this, just prodding around so just wanted to know the merit of the approach.
I would say that
to hack around and discover new stuff it is fun (do it yourself with std::bitset),
but in a serious development prefer using libraries like boost that will hasten your development and avoid errors. Moreover this library is open source and has been developed and read by hundred of professionals.

Matrix Libraries vs For Loops in C++

Could you tell me if using a matrix library results in a faster run-time than regular for-loops? Currently, I have some methods that use for-loops that iterate through multidimensional vectors to calculate matrix products and element-wise products, where the matrix size is roughly 1000 columns by 400 rows. This method is the most called method in my program and I would like to know if using a matrix library would increase the program's speed. Also, which library would you recommend (from http://eigen.tuxfamily.org/index.php?title=Benchmark, Eigen seems best to me)?
Thank You
Yes -- a fair number of C++ matrix libraries (E.g., MTL, uBLAS, Blitz++) use template metaprogramming to optimize their behavior. Absent a reason to do otherwise, I'd start with Boost uBlas. You might also want to look at the OO numerics libraries list for other possibilities.
I am trying to answer the question "should I" instead of "which one" because it isn't clear that you actually need such a library.
Would a matrix library improve execution time? Probably. The methods they teach you in high school are certainly not the fastest. However there are other issues to consider.
First, are you optimizing prematurely? Trying to make your program as fast as possible as soon as possible is tempting, but not always the right thing to do. You have to make the determination if doing so is really a valid way to spend your time.
Second, will speed have any significant effect on usability? Making a program work in 2 seconds instead of 4 seconds isn't really worth the effort.... but 30 hours instead of 60 hours? Maybe so. I like to put emphasis on getting everything working before doing the polishing.
Finally, I have met several examples of code somebody else wrote several years before which was utterly useless. Old libraries that couldn't be found or compiled with a new OS or compiler or something different meant that I had to completely rewrite something wasting weeks of my time. It may have seemed like a good idea originally to get that extra few percent performance, but it meant that their code had a limited life span, especially because of poor documentation.
Keep It Simple Stupid is an excellent mantra for so many things. I am a strong advocate for only using libraries when absolutely necessary, and then only using those which seem to be long lived and stable.

What advantages does modern Fortran have over modern C++? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm trying to decide between Fortran and C++ for an application in scientific computing. It's not clear to me if Fortran still has advantages over other languages when it comes to performance. For example, I believe since Fortran enforces strict aliasing, better optimizations could be made by the compiler when compared to C before C99. I'm unsure of how C++ fits in here.
Any guidance?
I took a look at some of the stuff in the latest Fortran standards, and frankly I'm impressed. A lot of what I hated about the language 20 years ago is gone now. No more line numbers and special columns (may they burn in hell).
Fortran has been heavily used in engineering circles for 50 years now. That gives you two advantages if you work in those circles. First off, these folks care a lot about optimization. That means Fortran compilers tend to have the best optimizers around. The language itself is a lot more optimizable than Cish languages too, thanks to its lack of aliasing.
The second advantage is that Fortran's library support for number crunching simply cannot be beat. The best code is nearly always going to be the well-debugged code you don't have to write.
If your application doesn't fall under scientific, engineering, or number crunching in general, then neither of the above will be a big deal for you, so you may be better off looking elsewhere.
The other major issue is the learning curve which is very huge for C++ and exceptionally small for Fortran (90 and later). Fortran is like MATLAB with operations like ...
B'DB is matmul( matmul(transpose(B), D), B )
L2 norm of a vector is norm2(x)
SVD of a matrix using LAPACK is call gesvd(A,S,u,vt)
Fortran also has pointers, dynamic memory, user defined data types etc.
It is well supported by major vendors (Intel/Sun/IBM/Cray/PGI/NAG etc.), open source (gfortan/g95) communities and developers of numerical library/APIs such as PETSc, MPI etc.
Heck the new standard (Fortran 2008) even has co-arrays for doing parallel programming without the need for MPI/OpenMP and some Fortran compilers already support it (g95 and Cray).
Basically it has all the good qualities required for numerical computing, is easier than MATLAB, is standardized, free, scalable (with MPI/OpenMP and co-arrays), produces blazing fast/parallel code.
For numerics nothing beats Fortran but unfortunately for anything else everything beats Fortan. So if you are a scientist with a safe job and only do numerical/HPC computing then stick with Fortran otherwise learn and use C++ as it is widely used for non numerical software.
Fortran allows whole array operations and also operations on array sections. There are C++ classes for arrays, but I don't think you can refer to a slice such as x(:,2:,1:N3:2) as easily as in Fortran. This lets one express some algorithms pretty concisely.
The convenience of Fortran's array operations extends to arrays of derived types. Suppose you have a an array of dates:
type date
integer :: month,day,year
end type date
type(date) :: x(1000)
Then x refers to the array of dates, x%month refers to the array of months, and pack(x,x%month==1) refers to all dates in January. How many other programming languages offer this convenience?
Some of the earlier comments about Fortran -- "old and disgusting" -- are biased and should be discounted accordingly. Let me argue the opposite. In my opinion the free format of Fortran 90 looks better than the syntax of C and C++, with the curly braces and semicolons. Leaving them out or incorrectly putting them in can cause errors in C and C++ that have no counterpart in Fortran.
Fortran has been highly optimized for mathematical (especially matrix) like operations.
C++ has been highly optimized for object usage.
Which is more important to you.
As noted below C++ has an optimized matrix library.
But Fortran's whole purpose is optimization of mathematical processes (especially matrix operations). The fact that these optimizations are built into the foundation of the language (rather than a library) and have about a two decade head start on research over C++ I doubt (but don't know for a fact) that in this area Fortran is going to win hands down.
Advantages of fortran95 and above over c++(2003):
As previously(by user4562) mentioned short learning curve(my first language was C and i still can't master it , similar is true for C++)
(My personal opinion) Easy for code transition from Octave(for that matter Matlab)similar syntax,same modularity[I use Octave to prototype a program and rewrite in fortran95 for speed],though u can directly use octave code in C++.
dynamic memory allocation is quite straight forward.(f77 didn't have this at all!)
libraries support (u can do this in c++ as well , but its natural to use fortran)
Co-array support for parallel computing (pity only cray supports them as of feb 2011 gfortran work has started as of gfortran4.6 but still a long way to go)
in short if your program or application is purely scientific computation use fortran 95 and above if calculating a few numbers is just part of the story use C++ (or whatever u feel is better)
I am new to programming.I have been programming in the field of finite elements for about a year. After some research on the net I decided to use fortran 2003.I learned to program in the modular style in about ten days by studying the Chapman book. It's one year on and i have written about four thousands of code lines in modular format(maintainable,reusable and neat codes) and haven't used any character variable at all. I don't think that by studying C++,matlab,python,java ... for ten days you would be able to write numerical codes as efficient as in fortran. fortran 2003 also has all the necessary OOP capabilities which I am learning now.
So in terms of language strength in the numerical aspect fortan doesn't lack anything(modular style,OOP style,powerful array capabilities,powerful libraries, free and commercial up to dated compilers,very easy to learn, very efficient ...). Languages like python/numpy has most of these capabilities but lack efficiency. Languages like C++ also has most of the capabilities of fortran(although for array computation which is the main core of numerical computation you have to import some libraries!!), but maybe a program written by someone like me in fortran would be more efficient than one written by some c++ programmer with 10+ years of experience.
Finally I do my heavy numerical computations in fortran(modular or OOP format), and use python\numpy for small size computations(like creating plots,small size array computations ... ).
My experience with Fortran is that it's easy to learn, clean (being highly modularized), and thus well suited to a non-programmer whose main concern is doing highly optimized numerical computations. Although equal optimization can be performed in c++, (even perhaps to a greater extent), it takes a lot of instrinsic understanding to achieve those level of optimizations. When it comes to matrix calculations, out-of-the box a Fortran compiler will normally out-perform a c++ compiler. I'd also add that Fortran has keywords that are specifically designed to help the programmer to squeeze more performance out of a numerical routine. C++ has this too, but not to the extent Fortran does.
Another advantage is that Fortran is not operating system or architecture specific. In other words the Fortran code you write on one operating system or architecture should easily port to another where there is a Fortran compiler.
Another advantage is that modern Fortran is normally backwards compatible with older code bases of Fortran. And the code base that has been built over the years in Fortran is huge and extremely sophisticated (being mostly done by scientists and mathematicians).
Also, personally, I really enjoyed the built-in file handling functions that allow one to read a data file and perform operations on it almost instantly. Many other built-in functions in Fortran are designed to allow this convenience. C++ offers mainly building blocks to do this and this requires a bit of sweating it out just to read a data file b/c you need to know something about delimiters (where Fortran allows you to specify the delimiter).
Beyond this I can't think of advantages. Most anything else would be string manipulations, or algorithmic based operations to which c++ as a language, and in general it's compilers, are better suited and most often will perform better. A good knowledgeable programmer will likely prefer c++ as she/he would understand how to optimize a numerical routine in a way that could likely perform better than a Fortran compiled routine. Additionally good reliable Fortran compilers are not as easy to come by as good reliable C++ compilers.
IMHO, the only advantage that really matters is that programming FORTRAN allows you easier reuse of a lot of existing FORTRAN code and libraries. And if you have 50 FORTRAN programmers at hand for a project and a limited time frame, are you going first to teach them all C++, or will you accept to let them use their favorite language?
Given the existence of scientific computing packages like LAPACK++, which are highly optimized already, modern Fortran doesn't even have a performance advantage. C++ may have its faults, but performance is not one of them.
With the emergence of template-meta programming (especially expression templates), C++ reached FORTRAN's league in numerical computations, so speed should not be an issue anymore. However, there's still some things to be said about other issues:
Pro FORTRAN: The older folks might know it better than C++.
Contra FORTRAN: It's a disgusting, old, and mostly abandoned language, that's already outdated the moment your start your project. Whoever learns programming now, is very unlikely to learn FORTRAN, so you might run into problems finding programmers for the project later.
Pro C++: It's relatively modern, with compilers still improving in considerable strides. It allows you to write quite expressive code.
Contra C++: Some of those template error messages will make you weep.