C++ program for power but without using pow function [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm a newbee in C++ and I'm writing a C++ program that asks the user to input two integers and then it raises the first integer to the power specified by the second integer. For example, if the user enters 5 and 8, the result will be 5 subscript 8, i.e., number five will be raised to the eighth power. The program must not use any pre-defined C++ functions (like pow function) for this task. The program should allow the user to perform another calculation if they so desire. Can anyone help

I'm not going to give you any code, because that won't allow you to truly explore this concept. Rather, you should use this pseudo code to implement something on your own.
Create a function which accepts two inputs, the base and the exponent.
Now there are several ways to go about doing this. You can use efficient bit shifting, but let's start simple, shall we?
answer = base
i = 1
while i is less than or equal to exponent
answer = answer * base
return answer
Simply loop through multiplying the base by itself.
There are other ways that focus on efficiency. Look here to see something that you may want to attempt: are 2^n exponent calculations really less efficient than bit-shifts?

The program must not use any pre-defined C++ functions (like pow function) for this task
You can use some piece of c++ code like follows, to compute xy, without using any predefined function:
int x = 5;
int y = 3;
int result = 1;
for(int i = 0; i < y; ++i)
{
result *= x;
}
cout << result << endl;
Output:
125
See a working sample here.

Related

What is the best type to use for an index variable in a for loop in C++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
There have already been some questions on this topic (1, 2, 3). The thing is that there doesn't seem to be a clear-cut answer. Some answers suggest size_t (1, 2), some suggest ptrdiff_t (1, 2). Other options include int, uint32_t, auto or using decltype on .size() of a container or the member type size_type.
This question may seem unsuitable as being opinion-based, but I don't think that's the case. Just because there isn't already a consensus on which type to use, doesn't mean that there cannot exist an objective answer. This is due to the fact that the different choices aren't only aesthetical, but can actually influence the behavior of the code.
For example, using an index variable type with mismatched signedness in the loop condition will cause compiler warnings, like this. Also, using a type that has a range that is too small can cause an overflow, which in the case of signed types is UB. At the same time, in some cases changing the loop counter type can cause "crazy performance deviations".
I also wanted to find out what is the most popular, though not necessarily the best, way to create for loop, so I used GitHub* search to find out. Here are the results:
Loop type
Code result count on GitHub (averaged; "manual" loop + range-based)
for (int
15.8m
for (size_t
11.6m
for (auto
7.5m
for (uint32_t
2.3m
std::for_each
501k
for (ptrdiff_t
98.7k
for (decltype
77.5k
There are certainly large differences in occurrence count between the different loop types, however, there doesn't seem to be a clear outstanding leader.
As such I post this question asking, what is the best type to use for the index variable in a for loop in C++ or what are the rules or conditions based on which this type should be chosen?
*: The GitHub search tool produces varying results for "code results" (count) each time, so I averaged 26 values. As the search is text-based it includes both results of the form for (int i = 0; i < n; ++i) and for (int i : vec).

what is happening inside this factorial program? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i was just playing with the factorial question using recursion when i wrote the following code.
i know that i could directly return the factorial.however i created a variable result and wrote the code below.
now what i want to know is that haven't i created n (the no. i want to calculate the factorial of)no. of result variables in the process?? because whenever my function factorial is called ,result variable is created , and each of those result variables would hold some value.
long long factorial(long long param) {
long long result;
if (param == 1) return 1;
else {
result = param * factorial(param - 1);
}
return result;
}
i know this is not a good code and i didn't thought that this would give me the write answer .however to my surprise it is.i want to know what is going on in this program.
Your function is a recursive function. You can read about recursion, and about recursive debugging here:
https://www.programiz.com/cpp-programming/recursion
https://beginnersbook.com/2017/08/cpp-recursion/
First of all : your function is unable to determine 0!
Second, yes, without any optimization from the compiler your program will take up unnecessary resources. The function is called n times and so the stack grows n times. Within each stack frame a temporary result is pushed on the stack.
However, with this program being so small, it is very likely that a minimal compiler effort will optimize that away in a release build.
It is also possible to do a recursion without the stack growing : define your factorial in such a way that there are never temporary values involved. If f(n, a) := n == 0 ? a : f(n-1, n*a) then factorial(n) := f(n, 1)
This recursion just keeps an accumulated result, wich is a fine example of functional programming. The stack needn't grow.

Reason for using bit manipulation in array size [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have recently got a basic idea of bit manipulation, and I was going through a problem where I found this C++ statement:
int popcount[1<<16];
I do have a basic idea of left/right Bit shift, but I would like to know why it is used in array size place.
Unless you find a comment in the code and unless you find out what the intent of popcount is, one can just guess why one writes 1 << 16 instead of, for example, 65536.
A common case could be that you want to count the number of occurrences of a particular id in, for example, a file. If the range of such an id where 16 bits, then such code could look as follows. The [1<<16] then expresses that you expect a range of not more than 16 bits:
int popcounts[1<<16] = { 0 };
int main() {
uint16_t id;
while (myfile >> id) {
popcounts[id]++;
}
}
Note that this is more accurate than writing int popcounts[UINT_MAX], because UINT_MAX is guaranteed to be equal or greater than 65536, and it is not guaranteed to be exactly 65536.
1<<16 is a common way to write 2 ** 16, which is easier to verify and modify than the "magic number" 65536. You may also encounter things like 1000 * 1000 instead of 1000000 for the same reason (although C++14 allows for 1000'000).

The fastest way to get the sum of character orders? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm trying to find the fastest way to get the sum of a character orders in a string
for example if the string contains:
ABAACA;
Then the sum of character A will be:
(A=0)+(A=2)+(A=3)+(A=5)=10;
A=10;
i know some way to that but it takes too long,so would you please tell me how can i get the fastest sum?
Fastest way I see to do this with C++ (since there's nothing else describing your problem), involves parallel processing:
Parallel scan and in-place indexing
Reduction
Although it might not be what you were looking for.
Fastest non parallel solution:
-go over every char.
-increase count if match (if(ch=='A')count+=i;).
there is just no faster way, because you MUST visit each character.
Anyway if you have a working solution, it's probably the fastest already..
If no parallel tools are in place the fastest solution would be to just visit each char in loop and increase sum.
int count_match ( char* str, int length, char digit )
{
int output = 0;
for ( int index = 0; index < length; ++ index )
output += index & - (str[index] == digit);
return output;
}
If the length of the string could be known at compile time, then you could conceivably template that value out and let the compiler vectorize the loop for you.

Efficient way to find factorial [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the efficient way to find factorial of a number other than normal recursive function and loop method? Since the normal method takes too longer to produce output is there any way to reduce the time complexity than the recursive and loop methods?If not why?
Since 79! is 1.711E98 you only need a list of 79 numbers to just use a lookup table.
The factorials are listed at: http://www.tsm-resources.com/alists/fact.html in integer format or at http://home.ccil.org/~remlaps/javascript/jstest1.html in scientific format, so it is just "cut and paste"
If you want to calculate many factorial values, then caching the values as you go along is an option.
If you just one a single calculation of factorial(n), then loop is probably the best you can get. You could possibly get more out of the processor by a bit of loop unrolling (calculating two or four multiplications at once), but it's unlikely to work for very large factorials, since multiplication in itself becomes a lengthy series of instructions.
As far as I'm aware, there is no "magical" math to calculate a sequence of 12 * 13 * 14 * 15 or similar faster than multiplying them together.
You may use Stirling's approximation to evaluate a large factorial.
Since one of your comments says you want to find 100000!, this answer covers huge factorials.
If you do not need an exact answer you can use Stirling's Approximation
If you want an exact answer you need to use an arbitrary precision math package like GMP
arbitrary precision math package
No, not really. If you are concerned with the run-time cost, it can be reduced with a look-up table (which requires that you use pre-calculated values).
To store every factorial may require too much memory, so lets store every k:th factorial.
This will require the program to perform up to k multiplications in runtime.
Let's say your runtime performance requirement limits you to 1000 multiplications for each factorial. Then you need to pre-calculate and store 1000!, 2000!, 3000! and so on up to the upper limit you want to support (available memory will limit you).
Since factorials quickly become larger than the native data types you need a class that can handle large numbers. I have assumed that ther exists such a class and that it is called BigInteger.
BigInteger preCalculatedValues[] = { new BigInteger("1"), new BigInteger("<value of 1000!>"), and so on... }
BigInteger factorial(int n) {
int pre = n/1000;
int i;
if (pre > LARGEST_VALUE_HANDLED) {
// Either throw an exception or let it take longer. I choose to let it take longer.
pre = LARGEST_VALUE_HANDLED;
}
BigInteger result = preCalculatedValues[pre];
for (i = pre * 1000 + 1; i <= n; i++) {
result.multiplyWith(i); // This operation is probably overloaded on the * operator
}
}
The simplest way of calculating very large factorals is to use
the gamma function. On the other hand: it won't be as fast as
the table lookup (as proposed by others); if you're using built
in types, you'll need tables of:
for 32 bits: 12 entries
for 64 bits: 20 entries
for float: 34 entries
for double: 170 entries
(There may be an off by one error in the above tables. I wrote
the code to calculate them very quickly.)
For double, and possibly for float, the usual loop method
will probably introduce too many rounding errors anyway. If you
don't want to use a table, and you have C++11,
exp( lgamma( i + 1 ) ) should do the trick. (If you don't
have C++11, you might have the lgamma function anyway. It's
in C99.)
If you're dealing with some sort of extended range type, you
might have to implement lgamma (and exp) for your type.