Recursion solution for a number raised to an exponent - c++

Hey I have a problem were I have to solve x^n in a number of ways. One of them involves using a recursion formula and its giving me a hard time. So one of the ways I used recursion for x^n for n>=0
int power2(int base, int power){
if (power == 0)
return 1;
else if ( power == 1)
return base;
else
return (base * power2(base, power - 1));
}
this makes sense to me So when i set X = 2 and N = 4, it is decreasing the power, which is acting as a counter, and doing 2x2 power raised to 3, 4*2, power raised to 2, 8 *2 = 16. Than the power is raised to 1, and I have a base case were if the power is raised to 1 it just returns base. However for my next one I have to solve it using three formulas.
x0 = 1
xn if n is even = [xn/2]2
xn if n is odd = x * [xn/2]2
So what I have so far is
int power3(int base, int power){
if(power == 0){
return 1;
}
else if ( power == 1)
return base;
// if power is even
if (power % 2 == 0){
return base*(power3(base,(power/2)));
}
// if power is odd
else{
return 0;
}
}
So im just trying to get even numbers to work first, and when I set x=2 and n=4 it returns 8. Which makes sense to me, since when the power is 4/2 will only loop twice for being >1. So i really am trying to figure out a way to get this to loop one more time while staying true to the formula I was given.and when I added the odd base case now the program will work up untill n^5 but n^6 returns 32

You got a little problem with the interpretation of the formula.
x^n if n is even = [x^n/2]2 doesn't mean:
base*(power3(base,(power/2))) //meaning x * [x^n/2]
rather you'd have
(power3(base,(power/2))) * 2
looking at your formula again it isn't correct even and should be x^n if n is even = [x^n/2]^2
so as code:
(power3(base,(power/2))) * (power3(base,(power/2)))
or:
(power3(base * base,(power/2)))
Your whole function should probably be like this:
int power3(int base, int power){
if(power == 0){
return 1;
}
else if ( power == 1) // you don't really need this case,
return base; // power == 0 is enough as base case
// if power is even
if (power % 2 == 0){
return (power3(base * base,(power/2)));
}
// if power is odd
else{
return base * (power3(base * base,(power/2)));
}
}
Ok, since you seem to still be confused with the odd powers.
Your power variable is int so you get integer division meaning 3/2 = 1 instead of 1.5 (everything behind the decimal point gets truncated).
Now lets look at the odd case in the function:
return base * (power3(base * base,(power/2)));
lets assume base == 4 and power == 5
return 4 * (power3(4 * 4,(5/2))); // 5/2 evaluates to 2
is the same as saying return 4 * (power3(4, 5 - 1))
and then having return (power3(4 * 4, 4 /2)) since we now got an even case.
We basically just do these 2 steps as 1. I think my explanation sounds a bit weird but hope it helps.

Related

Error with two credit card numbers. Identifies the number as the wrong credit card type

These are my current errors, I think I did something wrong with the maths but everything I tried didn't work.
Ps: Sorry if my question's formatting is bad, first time using stackflow.
:) credit.c exists
:) credit.c compiles
:) identifies 378282246310005 as AMEX
:) identifies 371449635398431 as AMEX
:) identifies 5555555555554444 as MASTERCARD
:) identifies 5105105105105100 as MASTERCARD
:) identifies 4111111111111111 as VISA
:) identifies 4012888888881881 as VISA
:) identifies 4222222222222 as VISA
:) identifies 1234567890 as INVALID
:) identifies 369421438430814 as INVALID
:) identifies 4062901840 as INVALID
:) identifies 5673598276138003 as INVALID
:( identifies 4111111111111113 as INVALID
expected "INVALID\n", not "VISA\n"
:( identifies 4222222222223 as INVALID
expected "INVALID\n", not "VISA\n"
#include <cs50.h>
#include <math.h>
// Prompt user for credit card number
int main(void)
{
long credit_card, credit_number;
do
{
credit_card = get_long("Enter credit card number: ");
}
while (credit_card < 0);
credit_number = credit_card;
// Calculate total number of digits
int count = (credit_number == 0) ? 1 : (log10(credit_number) + 1);
int summation = 0;
while (credit_number == 0)
{
int x = credit_number % 10; summation += x;
int y = 2 * ((credit_number / 10) % 10);
int r = (y % 10) + floor((y / 10) % 10); summation += r; credit_number /= 100;
}
string card;
// Identify which card type you get after inputing your credit card number
int test = cc / pow(10, count - 2);
if ((count == 13 || count == 16) && test / 10 == 4)
{
card = "VISA";
}
else if (count == 16 && test >= 51 && test <= 55)
{
card = "MASTERCARD";
}
else if (count == 15 && (test == 34 || test == 37))
{
card = "AMEX";
}
else
{
card = "INVALID";
}
// Final verification
if (sum % 10 == 0)
{
printf("%s\n", card);
}
else
{
printf("INVALID\n");
}
}```
Your algorithm is maybe not fully correct. I would therefore propose a different approach. You can look at each single digit in a loop. And, you can also do the whole checksum calculation in one step.
I will show you how to do and explain the algorithm behind it.
BTW. Chosing the right algorithm is always the key for success.
So, first we need to think on how we can extract digits from a number. This can be done in a loop by repeating the follwoing steps:
Perform a modulo 10 division to get a digit
Do a integer division by 10
Repeat
Let us look at the example 1234.
Step 1 will get the 4 -- (1234 % 10 = 4)
Step 2 will convert original number into 123 -- (1234 / 10 = 123)
Step 1 will get the 3 -- (123 % 10 = 3)
Step 2 will convert the previous number into 12 -- (123 / 10 = 12)
Step 1 will get the 2 -- (12 % 10 = 2)
Step 2 will convert the previous number into 1 -- (12 / 10 = 1)
Step 1 will get the 1 -- (1 % 10 = 1)
Step 2 will convert the previous number into 0 -- (1 / 10 = 0)
Then the loop stops. Additionally we can observe that the loop stops, when the resulting divided becomes 0. And, we see addtionally that the number of loop executions is equal to the number of digits in the number. But this is somehow obvious.
OK, then let us look, what we learned so far
while (creditCardNumber > 0) {
unsigned int digit = creditCardNumber % 10;
creditCardNumber /= 10;
++countOfDigits;
}
This will get all digits and count them.
Good. Lets go to next step.
For later validation and comparison purpose we need to get the most significant digit (the first digit) and the second most significant digit (the second digit) of the number.
For this, we define 2 variables which will hold the number. We simply assign the current evaluated digit (and override it in each loop execution) to the "mostSignificantDigit". At the end of the loop, we will have it in our desired variable.
For the "secondMostSignificantDigit" we will simple copy the "old" or "previous" value of the "mostSignificantDigit", before assigning a new value to "mostSignificantDigit". With that, we will always have both values available.
The loop looks now like this:
while (creditCardNumber > 0) {
const unsigned int digit = creditCardNumber % 10;
secondMostSignificantDigit = mostSignificantDigit;
mostSignificantDigit = digit;
creditCardNumber /= 10;
++countOfDigits;
}
OK, now we come to the maybe more complex part. The cheksum. The calculation method is.
Start with the least significant (the last) digit
Do not multiply the digit, which is equivalent with multiplying it with 1, and add it to the checksum
Goto the next digit. Multiply it by 2. If the result is greater than 10, then get again the single digits and add both digits to the checksum
Repeat
So, the secret is, to analyze the somehow cryptic specification, given here. If we start with the last digit, we do not multiply it, the next digit will be multiplied, the next not and so on and so on.
To "not multiply" is the same as multiplying by 1. This means: In the loop we need to multiply alternating with 1 or with 2.
How to get alternating numbers in a loop? The algorithm for that is fairly simple. If you need alternating numbers, lets say, x,y,x,y,x,y,x..., Then, build the sum of x and y and perform the subtratcion "value = sum - value". Example:
We need alternating values 1 and 2. The sum is 3. To get the next value, we subtract the current value from the sum.
initial value = 1
sum = 3
current value = initial value = 1
next value = 3 - 1 = 2. Current value = 2
next value = 3 - 2 = 1. Current value = 1
next value = 3 - 1 = 2. Current value = 2
next value = 3 - 2 = 1. Current value = 1
next value = 3 - 1 = 2. Current value = 2
next value = 3 - 2 = 1. Current value = 1
. . .
Good, now we understand, how to make alternating values.
Next, If we multiply a digit with 2, then the maximum result maybe a 2 digit value. We get the single digits with a modulo and an integer division by 10.
And, now important, it does not matter, if we multiply or not, because, if we do not multiply, then the upper digit will always be 0. And this will not contribute to the sum.
With all that, we can always do a multiplication and always split the result into 2 digits (many of them having the upper digit 0).
The result will be:
checkSum += (digit * multiplier) % 10 + (digit * multiplier) / 10;
multiplier = 3 - multiplier;
An astonishingly simple formula.
Next, if we know C or C++ we also know that a multiplication with 2 can be done very efficiently with a bit shift left. And, additionally, a "no-multiplication" can be done with a bit shift 0. That is extremely efficient and faster than multiplication.
x * 1 is identical with x << 0
x * 2 is identical with x << 1
For the final result we will use this mechanism, alternate the multiplier between 0 and 1 and do shifts.
This will give us a very effective checksum calculation.
At the end of the program, we will use all gathered values and compare them to the specification.
Thsi will lead to:
int main() {
// Get the credit card number. Unfortunately I do not know CS50. I use the C++ standard iostream lib.
// Please replace the following 4 lines with your CS50 equivalent
unsigned long long creditCardNumber;
std::cout << "Enter credit card number: ";
std::cin >> creditCardNumber;
std::cout << "\n\n";
// We need to count the number of digits for validation
unsigned int countOfDigits = 0;
// Here we will calculate the checksum
unsigned int checkSum = 0;
// We need to multiply digits with 1 or with 2
unsigned int multiplier = 0;
// For validation purposes we need the most significant 2 digits
unsigned int mostSignificantDigit = 0;
unsigned int secondMostSignificantDigit = 0;
// Now we get all digits from the credit card number in a loop
while (creditCardNumber > 0) {
// Get the least significant digits (for 1234 it will be 4)
const unsigned int digit = creditCardNumber % 10;
// Now we have one digit more. In the end we will have the number of all digits
++countOfDigits;
// Simply remember the most significant digits
secondMostSignificantDigit = mostSignificantDigit;
mostSignificantDigit = digit;
// Calculate the checksum
checkSum += (digit << multiplier) % 10 + (digit << multiplier) / 10;
// Multiplier for next loop
multiplier = 1 - multiplier;
creditCardNumber /= 10;
}
// Get the least significant digit of the checksum
checkSum %= 10;
// Validate all calculated values and show the result
if ((0 == checkSum) && // Checksum must be correct AND
(15 == countOfDigits) && // Count of digits must be correct AND
((3 == mostSignificantDigit) && // Most significant digits must be correct
((4 == secondMostSignificantDigit) || (7 == secondMostSignificantDigit)))) {
std::cout << "AMEX\n";
}
else if ((0 == checkSum) && // Checksum must be correct AND
(16 == countOfDigits) && // Count of digits must be correct AND
((5 == mostSignificantDigit) && // Most significant digits must be correct
((secondMostSignificantDigit > 0) && (secondMostSignificantDigit < 6)))) {
std::cout << "MASTERCARD\n";
}
else if ((0 == checkSum) && // Checksum must be correct AND
((16 == countOfDigits) || (13 == countOfDigits)) && // Count of digits must be correct AND
((4 == mostSignificantDigit))) { // Most significant digit must be correct
std::cout << "VISA\n";
}
else {
std::cout << "INVALID\n";
}
return 0;
}
What we learn with this example, is integer division and modulo division and the smart usage of the identity element for binary operations.
In case of questions, please ask
Just to be complete, I will show you a C++ solution, based on a std::string and using modern C++ elements and algorithms.
For example, the whole checksum calculation will be done with one statement. The whole program does not contain any loop.
#include <iostream>
#include <string>
#include <regex>
#include <numeric>
int main() {
// ---------------------------------------------------------------------------------------------------
// Get user input
// Inform user, what to do. Enter a credit card number. We are a little tolerant with the input format
std::cout << "\nPlease enter a credit card number:\t";
// Get the number, in any format from the user
std::string creditCardNumber{};
std::getline(std::cin, creditCardNumber);
// Remove the noise, meaning, all non digits from the credit card number
creditCardNumber = std::regex_replace(creditCardNumber, std::regex(R"(\D)"), "");
// ---------------------------------------------------------------------------------------------------
// Calculate checksum
unsigned int checksum = std::accumulate(creditCardNumber.rbegin(), creditCardNumber.rend(), 0U,
[multiplier = 1U](const unsigned int sum, const char digit) mutable -> unsigned int {
multiplier = 1 - multiplier; unsigned int value = digit - '0';
return sum + ((value << multiplier) % 10) + ((value << multiplier) / 10); });
// We are only interested in the lowest digit
checksum %= 10;
// ---------------------------------------------------------------------------------------------------
// Validation and output
if ((0 == checksum) && // Checksum must be correct AND
(15 == creditCardNumber.length()) && // Count of digits must be correct AND
(('3' == creditCardNumber[0]) && // Most significant digits must be correct
(('4' == creditCardNumber[1]) || ('7' == creditCardNumber[1])))) {
std::cout << "AMEX\n";
}
else if ((0 == checksum) && // Checksum must be correct AND
(16 == creditCardNumber.length()) && // Count of digits must be correct AND
(('5' == creditCardNumber[0]) && // Most significant digits must be correct
((creditCardNumber[1] > '0') && (creditCardNumber[1] < '6')))) {
std::cout << "MASTERCARD\n";
}
else if ((0 == checksum) && // Checksum must be correct AND
((16 == creditCardNumber.length()) || (13 == creditCardNumber.length())) && // Count of digits must be correct AND
(('4' == creditCardNumber[0]))) { // Most significant digit must be correct
std::cout << "VISA\n";
}
else {
std::cout << "INVALID\n";
}
return 0;

Compute Power(x,y) code clarification C++

int Power(double x, double y) {
long long power = y;
double result = 1.0;
if (y<0) {
power = -power;
x = 1 / x;
}
while (power) {
if (power & 1) {
result *= x;
}
x *= x;
power >>= 1;
}
std::cout << result;
return result;
}
I am seeking clarification about this code. Here are a few questions I have about the code
When the power is negative where is it multiplying 1/(x*y)?
In the if statement inside the while loop it tests to see if power%2 == 0 but if it is not mod 2 then where is that calculation taking place?
If someone can clarify through an example like x = 2 and y = 4 and show how the program runs to calculate the power to be 16 that will be really helpful.
I am new to programming so trying to understand basic primitive types with these examples. Thank you in advance.
When the power is negative where is it multiplying 1/(x*y)?
Nowhere. When y is negative the code uses power = -power; x = 1 / x;.
In the if statement inside the while loop it tests to see if power%2 == 0 but if it is not mod 2 then where is that calculation taking place?
No it doesn't. The code does not check if the power is even. It does check if the power is odd:
if (power & 1) {
result *= x;
}
What is left now is even and if you consider that (x^2n) == (x^n)^2 then you will understand why the code continues with:
x *= x;
power >>= 1;
For example power was 5 then the odd power is handled by result*=x;, we have 4 left, and x^4 is the same as (x^2)^2 so we can coninue the loop with power divided by 2 and x replaced by x^2.
If someone can clarify through an example like x = 2 and y = 4 and show how the program runs to calculate the power to be 16 that will be really helpful.
You should take this opportunity to learn how to use a debugger. If you want to step through code to see what each line does: debugger.
PS: the code is almost "ok-ish". What is not ok at all is the mess about types. double y is assigned to long long power and double result is returned as int. All this makes no sense. The function does not correctly calculate floating-point powers. As this is just an exercise, I would recommend to use int everywhere and concentrate on integers for now. Last but not least, note that this is code one actually should not write, because someone did it already: std::pow.

How to store output of very large Fibonacci number?

I am making a program for nth Fibonacci number. I made the following program using recursion and memoization.
The main problem is that the value of n can go up to 10000 which means that the Fibonacci number of 10000 would be more than 2000 digit long.
With a little bit of googling, I found that i could use arrays and store every digit of the solution in an element of the array but I am still not able to figure out how to implement this approach with my program.
#include<iostream>
using namespace std;
long long int memo[101000];
long long int n;
long long int fib(long long int n)
{
if(n==1 || n==2)
return 1;
if(memo[n]!=0)
return memo[n];
return memo[n] = fib(n-1) + fib(n-2);
}
int main()
{
cin>>n;
long long int ans = fib(n);
cout<<ans;
}
How do I implement that approach or if there is another method that can be used to achieve such large values?
One thing that I think should be pointed out is there's other ways to implement fib that are much easier for something like C++ to compute
consider the following pseudo code
function fib (n) {
let a = 0, b = 1, _;
while (n > 0) {
_ = a;
a = b;
b = b + _;
n = n - 1;
}
return a;
}
This doesn't require memoisation and you don't have to be concerned about blowing up your stack with too many recursive calls. Recursion is a really powerful looping construct but it's one of those fubu things that's best left to langs like Lisp, Scheme, Kotlin, Lua (and a few others) that support it so elegantly.
That's not to say tail call elimination is impossible in C++, but unless you're doing something to optimise/compile for it explicitly, I'm doubtful that whatever compiler you're using would support it by default.
As for computing the exceptionally large numbers, you'll have to either get creative doing adding The Hard Way or rely upon an arbitrary precision arithmetic library like GMP. I'm sure there's other libs for this too.
Adding The Hard Way™
Remember how you used to add big numbers when you were a little tater tot, fresh off the aluminum foil?
5-year-old math
1259601512351095520986368
+ 50695640938240596831104
---------------------------
?
Well you gotta add each column, right to left. And when a column overflows into the double digits, remember to carry that 1 over to the next column.
... <-001
1259601512351095520986368
+ 50695640938240596831104
---------------------------
... <-472
The 10,000th fibonacci number is thousands of digits long, so there's no way that's going to fit in any integer C++ provides out of the box. So without relying upon a library, you could use a string or an array of single-digit numbers. To output the final number, you'll have to convert it to a string tho.
(woflram alpha: fibonacci 10000)
Doing it this way, you'll perform a couple million single-digit additions; it might take a while, but it should be a breeze for any modern computer to handle. Time to get to work !
Here's an example in of a Bignum module in JavaScript
const Bignum =
{ fromInt: (n = 0) =>
n < 10
? [ n ]
: [ n % 10, ...Bignum.fromInt (n / 10 >> 0) ]
, fromString: (s = "0") =>
Array.from (s, Number) .reverse ()
, toString: (b) =>
b .reverse () .join ("")
, add: (b1, b2) =>
{
const len = Math.max (b1.length, b2.length)
let answer = []
let carry = 0
for (let i = 0; i < len; i = i + 1) {
const x = b1[i] || 0
const y = b2[i] || 0
const sum = x + y + carry
answer.push (sum % 10)
carry = sum / 10 >> 0
}
if (carry > 0) answer.push (carry)
return answer
}
}
We can verify that the Wolfram Alpha answer above is correct
const { fromInt, toString, add } =
Bignum
const bigfib = (n = 0) =>
{
let a = fromInt (0)
let b = fromInt (1)
let _
while (n > 0) {
_ = a
a = b
b = add (b, _)
n = n - 1
}
return toString (a)
}
bigfib (10000)
// "336447 ... 366875"
Expand the program below to run it in your browser
const Bignum =
{ fromInt: (n = 0) =>
n < 10
? [ n ]
: [ n % 10, ...Bignum.fromInt (n / 10 >> 0) ]
, fromString: (s = "0") =>
Array.from (s) .reverse ()
, toString: (b) =>
b .reverse () .join ("")
, add: (b1, b2) =>
{
const len = Math.max (b1.length, b2.length)
let answer = []
let carry = 0
for (let i = 0; i < len; i = i + 1) {
const x = b1[i] || 0
const y = b2[i] || 0
const sum = x + y + carry
answer.push (sum % 10)
carry = sum / 10 >> 0
}
if (carry > 0) answer.push (carry)
return answer
}
}
const { fromInt, toString, add } =
Bignum
const bigfib = (n = 0) =>
{
let a = fromInt (0)
let b = fromInt (1)
let _
while (n > 0) {
_ = a
a = b
b = add (b, _)
n = n - 1
}
return toString (a)
}
console.log (bigfib (10000))
Try not to use recursion for a simple problem like fibonacci. And if you'll only use it once, don't use an array to store all results. An array of 2 elements containing the 2 previous fibonacci numbers will be enough. In each step, you then only have to sum up those 2 numbers. How can you save 2 consecutive fibonacci numbers? Well, you know that when you have 2 consecutive integers one is even and one is odd. So you can use that property to know where to get/place a fibonacci number: for fib(i), if i is even (i%2 is 0) place it in the first element of the array (index 0), else (i%2 is then 1) place it in the second element(index 1). Why can you just place it there? Well when you're calculating fib(i), the value that is on the place fib(i) should go is fib(i-2) (because (i-2)%2 is the same as i%2). But you won't need fib(i-2) any more: fib(i+1) only needs fib(i-1)(that's still in the array) and fib(i)(that just got inserted in the array).
So you could replace the recursion calls with a for loop like this:
int fibonacci(int n){
if( n <= 0){
return 0;
}
int previous[] = {0, 1}; // start with fib(0) and fib(1)
for(int i = 2; i <= n; ++i){
// modulo can be implemented with bit operations(much faster): i % 2 = i & 1
previous[i&1] += previous[(i-1)&1]; //shorter way to say: previous[i&1] = previous[i&1] + previous[(i-1)&1]
}
//Result is in previous[n&1]
return previous[n&1];
}
Recursion is actually discommanded while programming because of the time(function calls) and ressources(stack) it consumes. So each time you use recursion, try to replace it with a loop and a stack with simple pop/push operations if needed to save the "current position" (in c++ one can use a vector). In the case of the fibonacci, the stack isn't even needed but if you are iterating over a tree datastructure for example you'll need a stack (depends on the implementation though). As I was looking for my solution, I saw #naomik provided a solution with the while loop. That one is fine too, but I prefer the array with the modulo operation (a bit shorter).
Now concerning the problem of the size long long int has, it can be solved by using external libraries that implement operations for big numbers (like the GMP library or Boost.multiprecision). But you could also create your own version of a BigInteger-like class from Java and implement the basic operations like the one I have. I've only implemented the addition in my example (try to implement the others they are quite similar).
The main idea is simple, a BigInt represents a big decimal number by cutting its little endian representation into pieces (I'll explain why little endian at the end). The length of those pieces depends on the base you choose. If you want to work with decimal representations, it will only work if your base is a power of 10: if you choose 10 as base each piece will represent one digit, if you choose 100 (= 10^2) as base each piece will represent two consecutive digits starting from the end(see little endian), if you choose 1000 as base (10^3) each piece will represent three consecutive digits, ... and so on. Let's say that you have base 100, 12765 will then be [65, 27, 1], 1789 will be [89, 17], 505 will be [5, 5] (= [05,5]), ... with base 1000: 12765 would be [765, 12], 1789 would be [789, 1], 505 would be [505]. It's not the most efficient, but it is the most intuitive (I think ...)
The addition is then a bit like the addition on paper we learned at school:
begin with the lowest piece of the BigInt
add it with the corresponding piece of the other one
the lowest piece of that sum(= the sum modulus the base) becomes the corresponding piece of the final result
the "bigger" pieces of that sum will be added ("carried") to the sum of the following pieces
go to step 2 with next piece
if no piece left, add the carry and the remaining bigger pieces of the other BigInt (if it has pieces left)
For example:
9542 + 1097855 = [42, 95] + [55, 78, 09, 1]
lowest piece = 42 and 55 --> 42 + 55 = 97 = [97]
---> lowest piece of result = 97 (no carry, carry = 0)
2nd piece = 95 and 78 --> (95+78) + 0 = 173 = [73, 1]
---> 2nd piece of final result = 73
---> remaining: [1] = 1 = carry (will be added to sum of following pieces)
no piece left in first `BigInt`!
--> add carry ( [1] ) and remaining pieces from second `BigInt`( [9, 1] ) to final result
--> first additional piece: 9 + 1 = 10 = [10] (no carry)
--> second additional piece: 1 + 0 = 1 = [1] (no carry)
==> 9542 + 1 097 855 = [42, 95] + [55, 78, 09, 1] = [97, 73, 10, 1] = 1 107 397
Here is a demo where I used the class above to calculate the fibonacci of 10000 (result is too big to copy here)
Good luck!
PS: Why little endian? For the ease of the implementation: it allows to use push_back when adding digits and iteration while implementing the operations will start from the first piece instead of the last piece in the array.

How can I account for a decimal using the modulus operator

The project I am working on needs to find some way of verifying that a variable after the modulus operation is either number != 0, number > 0, or number < (0 < x < 1). I have the first two understood, however employing the mod operator to accomplish the third is difficult.
Essentially what I am looking to do is to be able to catch a value similar to something like this:
a) 2 % 6
b) flag it and store the fact that .333 is less than 1 in a variable (bool)
c) perform a follow up action on the basis that the variable returned a value less than 1.
I have a feeling that the mod operator cannot perform this by itself. I'm looking for a way to utilize its ability to find remainders in order to produce a result.
edit: Here is some context. Obveously the below code will not give me what I want.
if (((inGameTotalCoins-1) % (maxPerTurn+1)) < 0){
computerTakenCoins = (inGameTotalCoins - 1);
inGameTotalCoins = 1;
The quotient is 0(2/6) with the fractional part discarded.The fractional part is .3333 ... So you are basically talking about the fractional part of the quotient , not the modulus value. Modulus can be calculated as follows :
(a / b) * b + (a % b) = a
(2 / 6) * 6 + (2 % 6) = 2
0 * 6 + (2 % 7) = 2
(2 % 6) = 2
*6 goes into 2 zero times with 2 left over.
How about this:-
int number1 = 2;
int number2 = 6;
float number3 = static_cast<float>(number1) / static_cast<float>(number2);
bool isfraction = number3 > 0 && number3 < 1;
if(isfraction){
std :: cout << "true\n" << number3;
}
else{
std :: cout << "false" << number3;
}
number != 0 includes number > 0 and number < (0 x < 1). And number > 0 includes number < (0 x < 1). Generally we do not classify so. For example, people classify number > 0, number == 0 and number < 0.
If you do the modulous operation, you get remainder. Remainder's definition is not one thing. You can see it at https://en.m.wikipedia.org/wiki/Remainder

Understanding Recursion, c++

For the code below, could anyone please tell me why the function always returns "0" if the return value for the base case (n==0) is 0? I know in order to correct this function, I'd simply have to replace "return 0" with "return 1", however, I'm trying to understand why does it return 0 for the base case below.
Thanks for your help
int factorial(int n) {
if (n == 0) {
return 0;
} else {
return n * factorial(n-1);
}
}
Edit: Hopefully, the code below has no logical errors ...
#include<iostream>
#include<math.h>
using namespace std;
long double factorial (long double n) {
if (n==0) return 1;
if (n<0) return -fabs((n*factorial(n+1)));
return n*(factorial(n-1));
}
int main () {
long double n;
cout << "Enter a number: ";
cin >> n;
cout << "Factorial of " << n << " is " << factorial(n) <<endl;
return 0;
}
If you take a look at how the factorial is defined you'll find something like:
f(0) = 1
f(1) = 1
f(n) = f(n-1) * n
So your function does indeed return the wrong value for factorial(0). The recursion in this function basically works by decrementing n in every new function call of factorial.
Let's assume you call factorial(3). n would that with 3, the else branch will get executed as n does not equal zero. We follow the third rule of our definition an call factorial(2) (which is n-1) and multiply the result of it by n. Your function will step down until factorial(0) is called and returns 0 which then is a factor of all previous calculations, resulting in 3*2*1*0, and that equals to 0.
This code is simply wrong. No matter which n > 0 it gets as argument, every value is eventually multiplied with 0 and therefore factorial( n ) = 0 for all n > 0.
It returns zero since any number times zero is zero. You start with some number n, say n=5. As you go through the recursion you have:
n * factorial(n-1)
5 * factorial(5-1)
5 * 4 * factorial(4-1)
5 * 4 * 3 * factorial(3-1)
5 * 4 * 3 * 2 * factorial(2-1)
5 * 4 * 3 * 2 * 1 * factorial(1-1)
But factorial(1-1) is factorial(0) which returns 0, so you get :
5 * 4 * 3 * 2 * 1 * 0 = 0
For the code below, could anyone please tell me why the function returns "0" if the return value for the base case (n==0) is 0?
Someone chose to do that. You'd have to ask the author why they did that.
I know in order to correct this function, I'd simply have to replace "return 0" with "return 1", however, I'm trying to understand why does it return 0 for the base case below.
Likely because the person who wrote it thought 0! was equal to 0.
I don't get you question entirely but lets cal the function f(int n): int okey to make it shorter
for n = 0 it will return 0 becaulse thats what you told it to do right: if(n == 0) return 0;
for n + 1 youll get the folowing pattern:
f(n+1) ==> n * f(n) becaulse thats wat you told it to do otherwise right? and f again will evaluate.
so thats why youre function will return 0 in any case and if you alter the base case to 1 youll get:
For whatever n (bigger than or equal to 0), you multiply a lot of numbers down to factorial(0) which returns 0.
The result of
n*(n-1)*(n-2)*...*3*2*1*0
is a big fat 0
P.S. Besides not computing properly, the code has a major flaw. If you give it a negative number, you make it cry.