Boolean recursive function returning the wrong value - c++

This is a recursive function I did to find out if the given digits in a number are in a decreasing order, I'm sure my base is correct as I see the function does return false for the first few digits, but because the last two are in a decreasing order the function returns true in the end.
I can't figure out how to keep that false value and return it back to the original call for the function.
#include<iostream>
using namespace std;
bool dec(int n);
void main()
{
cout << dec(1231);
}
bool dec(int n)
{
bool res;
if (n < 10)
return true;
else
{
res = dec(n / 10);
if ((n / 10) % 10 > n % 10)
return true;
else
return false;
}
}

You should only return true if res is also true. Try
return (res && (n / 10) % 10 > n % 10);

Related

How do I make an ascending function in C++?

I need to make a simple function in c++ that will say if an entered integer has its digits ascending from left to right. Ex, 123 is ascending. We just started learning recurssion, which is what I'm supposed to use, but I'm confused. So far what I was thinking is that you store the last digit as a temp, then compare that to the next digit, but how would you manage to do that?
bool ascending(int n) {
int temp = n % 10;
while (n / 10 > 0) {
n = n / 10;
if (temp > n % 10) {
return false;
break;
}
temp = n % 10;
}
}
This is the code I have so far, but I'm definitely messing up. I'm not even using recurrsion.
Here is one way you can go about it.
On every iteration, you check that last 2 digits are in order. And when the number is a single digit, return true
bool ascending(int n) {
int last_digit = n % 10;
int remainder = n / 10;
if (remainder == 0)
{
return true;
}
int second_last_digit = remainder % 10;
if (last_digit < second_last_digit)
{
return false;
}
else
{
return ascending(remainder); // Recusrive call
}
}

Finding prime numbers in c++ [duplicate]

This question already has answers here:
C - determine if a number is prime
(12 answers)
Closed 4 years ago.
I'm currently learning c++ for the first time and I've written a cpp bool function to find if an integer is a prime number.
The code was:
bool isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
else
return true;
}
}
However, it turns out that 9 is also considered as a prime number with this function.
I found a solution just by removing the else statement,
bool isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
}
but I still don't get why the else statement had anything to do with it in the first place. Can anyone help me out?
Because of the if statement.
if (n % i == 0)
return false;
else
return true;
The condition reads "if n is divisible by the current number". The condition will either be true (in which case n is not prime) or false (it might be prime) so one of the branches must be taken and the function will exit in either case, possibly prematurely.
Removing the else prevents early return, however, it also prevents true being returned by the function. You can simply add return true to the end of the function:
bool isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true; // must be prime
}
The only way a number is prime is when the loop completes, so the return true; statement should be outside the loop. You only have to check numbers up to the square root of n.
Also, you need to handle the case where n is less than 2.
#include <cmath>
bool isPrime(int n)
{
if (n < 2)
{
return false;
}
for (int i = 2; i <= sqrt(n); i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
Because it will return in the first loop!
When the function enters the else, it will return true.
Any odd number will return true — and 9 is the first odd number bigger than 1 which is not a prime.
Try this:
bool isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
else
continue;
}
return true;
}
9 is odd. Which means it's not divisible by 2. In fact it's the first odd number after 1 that is not prime. Your code explicitly returns true if n is not divisible by 2.
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
else
return true;
}
The first time the for loop runs, i is 2. Either n % i == 0 is true or it is false. If true, your function immediately returns false. If false, your function immediately returns true.
You need to move the return true statement outside the loop. Only after checking all possible divisors by completing the for loop do you know if the number n is prime.

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;
}

Recursively check if all digits of a number are different

How can I check recursively if all the digits of an integer are different numbers in C++
void Check(int n)
{
if (n < 10)
return;
else
{
bool eq = !(n % 10 == ((n / 10) % 10));
if (eq == true)
{
Check(n / 10);
}
}
}
You can remember, which digits you have already seen. For instance by using a bool-array of length 10. At the first call of your function all entries are false. In each recursive call you set array[n%10] to true. If it was already true, then you have found a duplicate digit, otherwise not.
If you want to only use recursion, you can define a second recursive function:
bool checkIfDigitApearsInNumber(int n, int digit) {
if (n == 0) {
return false;
} else {
if (n % 10 == digit) {
return true;
} else {
return checkIfDigitApearsInNumber(n/10, digit);
}
}
}
In you function Check, you have to call this function in each step with n/10, n%10.

C++ Prime Number Program not recognizing 3? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My program is supposed to detect prime numbers from 1 to 100 and save them to a file.
For some reason, it does not recognize 3 but mistakenly recognizes some multiples (27, 33, etc) of 3 as prime.
Code follows...
/* This program will use a function determine if a number is prime.
When called this function will be used to determine all
prime numbers from 1- 100 and save them to a file*/
#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
bool isPrime(int);// function prototype
int main()
{
ofstream fout;
fout.open("prime.txt");
bool result;
int num; // variable to hold integer number
for (num = 1; num >= 1 && num <= 100; num++)
{
result =isPrime(num);
if (result == true)
{
fout << num<< endl;
}
else
{
cout << num << " is not prime." <<endl;
}
}
fout.close();
system("pause");
return 0;
}
bool isPrime(int test)
{
//define prime as a bool integer
bool prime;
// check for 2, a prime number that will not be caught by for loop algorithm
if (test == 2)
{
prime = true;
}
// eliminate all even numbers other than 2
else if ( test%2 == 0)
{
prime = false;
}
// eliminate 0
else if ( test == 0)
{
prime = false;
}
//eliminate 1, which is not prime or composite
else if ( test == 1)
{
prime = false;
}
// if test is not yet determined, check using algorithm
// this algorithm returns the remainder of a number (test)
// divided by an integer (i) in the range of i = 1
// to i = sqrt(number)
else
{
for(int i = 1; i <= (sqrt(test));i++)
{
if (test%i == 0)
{
prime = false;
}
else if (test%i != 0)
{
prime = true;
}
}
}
if (prime == true)
{
cout << "The number " <<test << " is prime." <<endl;
}
return prime;
EDIT for code fix:
/* This program will use a function determine if a number is prime.
When called this function will be used to determine all
prime numbers from 1- 100 and save them to a file*/
#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
bool isPrime(int);// function prototype
int main()
{
ofstream fout;
fout.open("prime.txt");
bool result;
int num; // variable to hold integer number
for (num = 1; num >= 1 && num <= 100; num++)
{
result =isPrime(num);
if (result == true)
{
fout << num<< endl;
}
else
{
cout << num << " is not prime." <<endl;
}
}
fout.close();
system("pause");
return 0;
}
bool isPrime(int test)
{
//define prime as a bool integer
bool prime;
double sqrt_num = sqrt(test);
//check for number 2 which algorithm wont catch, but is prime
if (test ==2)
{
return true;
}
// check if even and return false
else if ( test% 2 == 0)
{
return false;
}
//eliminate 1, which is not prime or composite, and 0.
else if ( test == 0 || test == 1)
{
return false;
}
// if test is not yet determined, check using algorithm
// this algorithm returns the remainder of a number (test)
// divided by an integer (i) in the range of i = 1
// to i = sqrt(number)
else
{
for(int i = 3; i <= sqrt_num;i+=2)
{
if (test%i == 0)
{
return false;
}
}
}
return true;
}
The biggest error in your code is your for-loop:
for(int i = 1; i <= (sqrt(test));i++)
{
if (test%i == 0)
{
prime = false;
}
else if (test%i != 0)
{
prime = true;
}
}
If we step through if for your false test cases 3 and 27, we see that for 3 it is this:
for (int i = 1; i <= 1; i++)
{
if (3 % 1 == 0)
{
prime = false;
}
else if (3 % 1 != 0)
{
prime = true;
}
}
The loop will be computed once, and the result (false) returned. The reason for this is that your loop starts with 1 and because every number is divisible by 1, every number which is only checked for 1 will always be composite. To fix this we just start with the number 2. If we do this, we have to set an initial value for "prime" because otherwise we would return a null value. Our initial value will be true, which means every number is prime until proven otherwise which, conveniently, is exactly what our for loop does.
The second error occurs when you reach the last iteration of the loop for 27:
//i == 5
for (int i = 1; i <= 5; i++)
{
if (27 % 5 == 0)
{
prime = false;
}
else if (27 % 5 != 0)
{
prime = true;
}
}
Because the last iteration sets prime to true, true is returned, which is obviously false. A possible solution is to exit the loop if we encounter an i for which number % i == 0 holds, as this means we have found a valid factor for said number.
TL; DR: Solving the errors we got:
start with the number 2 instead of one to get rid of the corner case 3 (and 2 as well)
if a valid factor is found the number is definitely composite and we set prime to false and exit the loop because we found a result.
Using the fixes and simplifying we get:
bool isPrime(int number)
{
// special cases 0 and 1
if (i == 0 || i == 1)
{
return false;
}
// else check from i = 2 to sqrt(number) if any of them divides the number
// if yes, the number is not prime and it returns false.
for (int i = 2; i <= sqrt(number); i++)
{
if (number % i == 0)
{
return false;
}
}
// if the number is not 0 or 1 and has passed the loop, it must be prime,
// hence we can return true
return true;
}
A small optimisation to make would be checking if it is even and if not just testing division by odd numbers. We would then replace the for-loop by:
if (number % 2 == 0)
{
return false;
}
for (int i = 3; i <= sqrt(number); i=i+2)
{
if (number % i == 0)
{
return false;
}
}
(int)sqrt(3) is 1, every test%1 will return 0 because division by 1 has no remainder.
You should stop the loop once you find proof that the number is not prime. If you keep it going the result will be misleading.
Note: sqrt() is an expensive function. Consider saving its result in a variable so you don't have to run it every loop.
Since you start the loop with i = 1, the condition test%i == 0 is always true.
So you should start it with i = 2, which will allow you to test numbers greater than or equal to 4.
In addition, you should break the loop once you set prime = false.
You will have to test 3 separately, since 2 > sqrt(3).
A few suggestions for improvement:
bool isPrime(int number)
{
// Handle 0 and 1
if (number < 2)
return false;
// Handle 2 and 3
if (number < 4)
return true;
// Handle numbers that are not adjacent to a multiple of 6
if (number%2==0 || number%3==0)
return false;
// Calculate once
int root = (int)sqrt(number);
// Check divisibility by numbers that are equal to -1(mod6)
for (int i=5; i<=root; i+=6)
{
if (number%i == 0)
return false;
}
// Check divisibility by numbers that are equal to +1(mod6)
for (int i=7; i<=root; i+=6)
{
if (number%i == 0)
return false;
}
return true;
}