Recursive/iterative functions - c++

I'm having a bit of a hard time creating a function, using iteration and recursion to find the sum of all even integers between 1 and the number the user inputs. The program guidelines require a function to solve this three ways:
a formula
iteration
recursion
This is what I have so far:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void formulaEvenSum(int num, int& evenSum)
{
evenSum = num / 2 * (num / 2 + 1);
return;
}
void loopEvenSum(int num, int& evenSum2)
{
}
int main()
{
int num, evenSum, evenSum2;
cout << "Program to compute sum of even integers from 1 to num.";
cout << endl << endl;
cout << "Enter a positive integer (or 0 to exit): ";
cin >> num;
formulaEvenSum(num, evenSum);
loopEvenSum(num, evenSum2);
cout << "Formula result = " << evenSum << endl;
cout << "Iterative result = " << evenSum2 << endl;
system("PAUSE");
return 0;
}

Using iteration to find the sum of even number is as given below.
void loopEvenSum(int num, int &evenSum2)
{
evenSum2=0;
for (i=2;i<=num;i++)
{
if(i%2==0)
evenSum2+=i;
}
}
The following code though not the most efficient can give you an idea how to write a recursive function.
void recursiveEvenSum(int num,int &evenSum3,int counter)
{
if(counter==1)
evenSum3=0;
if(counter>num)
return;
if(counter%2==0)
evenSum3+=counter;
recursiveEvenSum(num,evenSum3,counter+1);
}
Now you can call recursiveEvenSum(...) as
int evenSum3;
recursiveEvenSum(num,evenSum3,1);

You should be able to build an iterative solution using a for loop without too much problem.
A recursive solution might take the form:
f(a)
if(a>0)
return a+f(a-1)
else
return 0
f(user_input)
You have to differentiate between a case where you "dive deeper" and one wherein you provide an answer which doesn't affect the total, but begins the climb out of the recursion (though there are other ways to end it).
An alternative solution is a form:
f(a,sum,total)
if(a<=total)
return f(a+1,sum+a,total)
else
return sum
f(0,0,user_input)
The advantage of this second method is that some languages are able to recognise and optimize for what's known as "tail recursion". You'll see in the first recursive form that it's necessary to store an intermediate result for each level of recursion, but this is not necessary in the second form as all the information needed to return the final answer is passed along each time.
Hope this helps!

I think this does it Don't forget to initialize the value of evenSum1, evenSum2 and evenSum3 to 0 before calling the functions
void loopEvenSum(int num, int& evenSum2)
{
for(int i = num; i > 1; i--)
if(i%2 == 0)
evenSum2+=i;
}
void RecursiveEvenSum(int num, int & evenSum3)
{
if(num == 2)
{
evenSum3 + num;
return;
}
else
{
if(num%2 == 0)
evenSum3+=num;
num--;
RecursiveEvenSum(num, evenSum3);
}
}

void loopEvenSum(int num, int& evenSum2)
{
eventSum2 = 0;
for(int i = 1 ; i <= num; i++){
(i%2 == 0) eventSum += i;
}
}
void recurEvenSum(int num, int& evenSum3)
{
if(num == 1) return;
else if(num % 2 == 0) {
eventSum3 += num;
recurEvenSum(num-1, eventSum3);
}
else recurEvenSum(num-1, eventSum3);
}
btw, you have to initialize evenSum to 0 before calling methods.

the recursive method can be much simpler if you return int instead of void
void iterEvenSum(int num, int& evenSum2)
{
evenSum2 = 0;
if (num < 2) return;
for (int i = 0; i <= num; i+=2)
evenSum2 += i;
}
int recurEvenSum(int num)
{
if (num < 0) return 0;
if (num < 4) return 2;
return num - num%2 + recurEvenSum(num-2);
}

To get the sum of all numbers divisible by two in the set [1,num] by using an iterative approach, you can loop through all numbers in that range, starting from num until you reach 2, and add the number of the current iteration to the total sum, if this is divisible by two.
Please note that you have to assign zero to evenSum2 before starting the loop, otherwise the result will not be the same of formulaEvenSum().
void loopEvenSum(int num, int& evenSum2)
{
assert(num > 0);
evenSum2 = 0;
for (int i=num; i>=2; --i) {
if (0 == (i % 2)) {
evenSum2 += i;
}
}
}
To get the same result by using a recursive approach, instead of passing by reference the variable that will hold the sum, i suggest you to return the sum at each call; otherwise you'll need to hold a counter of the current recursion or, even worse, you'll need to set the sum to zero in the caller before starting the recursion.
int recursiveEventSum(int num)
{
assert(num > 0);
if (num == 1) {
return 0;
} else {
return ((num % 2) ? 0 : num) + recursiveEventSum(num-1);
}
}
Please note that, since you get an even number only if you subtract two (not one) from an even number, you could do optimisation by iterating only on those numbers, plus eventually, the first iteration if num was odd.

Related

How to get arbitrary return values in c++

I am trying to write divisor function, Which gives all divisor of given number. But in that I do not want any array rather I want to return every divisors one by one. Is it possible?
This is code :
auto allDivisor(int num){
for (int i=1; i<=num; i++){
if(num % i == 0){
return i;
}
}
But I got only first iterations result:
Enter integer number : 10 All divisior of 10 : 1
#include <iostream>
void allDivisor(int num, void (*callback)(int)) {
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
callback(i);
}
}
}
int main() {
int num = 10;
std::cout << "All divisors of " << num << ": ";
allDivisor(num, [](int divisor) {
std::cout << divisor << " ";
});
std::cout << std::endl;
return 0;
}
The callback function is passed to the allDivisor function as an argument, and it is called once for each divisor of the input number.
the usual way is to call your function multiple times and each time it will return different divisor until the end is marked by some special return value like 0 ... the iteration can be done either by passing i as function parameter or have it as global or static variable but that would make your function thread unsafe prohibiting to use it in parallel (even in serial overlapped with other division) ... It would look like this:
int allDivisor(int num)
{
static int i=0;
for (i++;i<=num;i++)
if ((num%i)==0) return i;
if (i>num){ i=0; return 0; }
}
and usage:
int d,X;
for (X=32;;)
{
d=allDivisor(X);
if (!d) break;
cout << d;
}
for (X=125;;)
{
d=allDivisor(X);
if (!d) break;
cout << d;
}
outputting this:
1
2
4
8
16
32
1
5
25
125
however be sure you always call the allDivisor until it returns 0 otherwise its next usage would be messedup (skipped first divisors until last i state) ... that could be repaired too for example like this (at cost of another static variable):
int allDivisor(int num)
{
static int i=0,n=0;
if (n!=num){ n=num; i=0; }
for (i++;i<=num;i++)
if ((num%i)==0) return i;
if (i>num){ i=0; n=0; return 0; }
}

C++ Gapful Numbers Crashing

I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?
Here's my code:
#include<math.h>
#include<stdlib.h>
using namespace std;
void gapful(int);
bool gapCheck(int);
int main(){
int n;
cout<<"Enter a top number: ";
cin>>n;
gapful(n);
system("pause");
return 0;
}
void gapful(int og){
for(int i=0; i<=og; i++){
fflush(stdin);
if(gapCheck(i)){
cout<<i<<" ";
}
}
}
bool gapCheck(int n){
int digits=0;
int n_save,n1,n2,n3;
if(n<100){
return false;
}
else{
n_save=n;
while(n>10){
n/=10;
digits++;
}
digits++;
n=n_save;
n1=n/pow(10, digits);
n2=n%10;
n3=n1*10 + n2;
if(n%n3 == 0){
return true;
}
else{
return false;
}
}
}
I'm open to any suggestions and comments, thank you. :)
For n == 110, you compute digits == 3. Then n1 == 110 / 1000 == 0, n2 == 110 % 10 == 0, n3 == 0*10 + 0 == 0, and finally n%n3 exhibits undefined behavior by way of division by zero.
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?
We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.
So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.
#include<math.h>
#include <iostream>
using namespace std;
void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);
int main(){
int n;
cout<<"Enter a top number: " << endl;
cin>>n;
gapful(n);
return 0;
}
void gapful(int og){
for(int i=1; i<=og; ++i){
if(gapCheck(i)){
cout<<i << '-' <<endl;
}
}
}
int getDigits(int number) {
int digitCount = 0;
while (number >= 10) {
++digitCount;
number /= 10;
}
return ++digitCount;
}
int digitAt(int number,int digit) {
int numOfDigits = getDigits(number);
int curDigit = 0;
if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
while (numOfDigits != digit) { //Count back to the digit requested
number /=10;
numOfDigits -=1;
}
curDigit = number%10; //Get the current digit to be returned.
} else {
throw "Digit requested is out of range!";
}
return curDigit;
}
bool gapCheck(int n){
int digitsN = getDigits(n);
if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
return false;
}
int first = digitAt(n,1) * 10; //Get the first number in the 10s place
int second = digitAt(n,digitsN); //Get the second number
int total = first + second; //Add them
return n % total == 0; //Return whether it evenly divides
}

remove odd numbers

I need to resolve this problme "Write a recursive function called removeCharge that receives an N number and returns a number that contains only the digits of the original number." I made it but now i don't know how to display the number in the same function.What can I do?
int newNumber=0;
int eliminareCifreImpare(int n){
if(n==0)
return 0;
eliminareCifreImpare(n/10);
int c=n%10;
if(c%2==0)
newNumber=newNumber*10+c;
}
I guess you are using a global variable because you don't properly understand how to return values from functions. You need to get a good understanding of how functions return values and how to use returned values before you try to write recursive functions.
Here's a working version
#include <iostream>
int eliminareCifreImpare(int n) {
if (n == 0)
return 0;
int newNumber = eliminareCifreImpare(n / 10);
int c = n % 10;
if (c % 2 == 0)
newNumber = newNumber * 10 + c;
return newNumber;
}
int main()
{
std::cout << eliminareCifreImpare(12345) << std::endl;
}

When i recurse the following code on function prime the program crashes what is wrong in my code?

Whenever I try to recurse in the function prime, my program crashes at that step. I think the problem is passing the function small as a recursion. What am I doing wrong?
#include <iostream>
using namespace std;
int smallest(int n) {
for( int x = 2 ; x <= n/2 ; x++){
if (n%x==0) {
return x;
}
else {
return 0;
}
}
}
int prime(int n, int(*small)(int)) {
int factor;
if (n == 1){
return 0;
}
else {
factor = n % small(n);
cout << small(n) << endl;
return prime(factor , small);
}
}
int main() {
prime(50 , &smallest);
return 0;
}
As the comments point out, when small returns 0, you continue recursing when you shouldn't. This can be solved with a small update to your base case:
if (n <= 1){
return 0 ;
}
Furthermore, it's worth pointing out that as it stands, your prime function will never call itself more than once. When you call smallest, you are guaranteed to get a prime number!

Programming a boolean program using recursion

I have this homework to do and I dont really understand why my program doesnt really work(prints 1 constantly).
I am supposed create a program that receives a number and a digit from the user(we can assume that the input is ok)
and it prints 1 in case the digit appears inside the number even times. In case it appears odd amount of times it will print 0.
I have to use a boolean recursion function.
can someone please tell me whats wrong with it?
#include <iostream>
using namespace std;
bool isEven(int num, int dig);
void main()
{
bool res;
int num, dig;
cout << "Please enter a number and a digit" << endl;
cin >> num >> dig;
cout << isEven(num, dig);
}
bool isEven(int num, int dig)
{
bool res;
int counter = 0;
if (num < 10)
{
if (counter % 2 != 0)
res=false;
else
res=true;
return res;
}
else
{
res=isEven(num / 10, dig);
if (num % 10 == dig)
counter++;
return res;
}
}
You're not passing the value of your counter down through your recursive calls - it's effectively unused in your current implementation.
You're also missing one check if dig % 10 == num - in your code, you never check the last digit of the number.
bool isEven(int num, int dig, int counter)
{
bool res;
if (num % 10 == dig)
counter++;
if (num < 10)
{
if (counter % 2 != 0)
res=false;
else
res=true;
return res;
}
else
{
res=isEven(num / 10, dig, counter);
return res;
}
}
And you can just call it with isEven(num, dig, 0) or create a wrapper function that takes just num and dig and calls this version with 0.
Note that there's a (imo) more elegant recursive expression of this function without using counters, although it's got some slightly unintuitive bits to it:
bool isEven(int num, int dig)
{
// Base case, single digit
// If num % 10 == dig on this last digit, we've got 1 match (odd, so return false)
if (num < 10)
return num % 10 != dig;
bool result = isEven(num / 10, dig);
if (num % 10 == dig) // This digit matches, count one more/flip the result
result = !result;
return result;
}