Related
I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".
I know both codes for prime and reverse numbers but I don't know how to merge them.
This is the code:
#include <iostream>
#include <conio.h>
using namespace std;
void prime_check(int x) {
int a, i, flag = 1;
cin >> a;
for (i = 2; i <= a / 2 && flag == 1; i++) {
if (a % i == 0)
flag = 0;
}
if (flag == 1)
cout << "prime";
else
break;
}
int main() {
int a, r, sum = 0;
cin >> a;
while (a != 0) {
r = a % 10;
sum = (sum * 10) + r;
a = a / 10;
}
}
The program has to check each digit of the number entered to see if it is prime or not in every step, then show "yes", but it doesn't work.
Welcome to the site.
I don't know how to merge them.
void prime_check(int n) { /*code*/ }
I'd understand that you don't know how to use this.
It's very easy!
int main()
{
int i = 0;
prime_check(i);
}
If you are confused about how the program executes, you could use a debugger to see where it goes. But since using a debugger can be a bit hard at first, I would suggest to add debug prints to see how the program executes.
This line of code prints the file and line number automatically.
std::cout << __FILE__ << ":" << __LINE__ << "\n";
I'd suggest to add it at the start of every function you wish to understand.
One step further is to make it into a macro, just so that it's easy to use.
#define DEBUGPRINT std::cout << __FILE__ << ":" << __LINE__ << "\n";
Check a working example here:
http://www.cpp.sh/2hpam
Note that it says <stdin>::14 instead of the filename because it's running on a webpage.
I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0, original; // added original variable, to store the number added
bool eachDigit = true; // added to keep track of each digit
cin >> a;
original = a;
while (a != 0) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && prime_check(original) && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
For optimization, you can check if the entered number is prime or not before starting that loop, and also you can break the loop right away if one of the digits of the entered number is not prime, Like this:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0;
bool eachDigit = true, entered; // added to keep track of each digit
cin >> a;
entered = prime_check(a);
while (a != 0 && entered && eachDigit) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && entered && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
Suppose you have an int variable num which you want to check for your conditions, you can achieve your target by the following:
int rev_num = 0;
bool flag = true; // Assuming 'num' satisfies your conditions, until proven otherwise
if (prime_check(num) == false) {
flag = false;
}
else while (num != 0) {
int digit = num % 10;
rev_num = rev_num * 10 + digit;
// Assuming your prime_check function returns 'true' and 'false'
if (prime_check(digit) == false) {
flag = false;
break;
}
num /= 10;
}
if (prime_check(rev_num) == false) {
flag = false;
}
if (flag) {
cout << "Number satisfies all conditions\n";
}
else {
cout << "Number does not satisfy all conditions\n";
}
The problem is that each of your functions is doing three things, 1) inputting the number, 2) testing the number and 3) outputting the result. To combine these functions you need to have two functions that are only testing the number. Then you can use both functions on the same number, instead of inputting two different numbers and printing two different results. You will need to use function parameters, to pass the input number to the two functions, and function return values to return the result of the test. The inputting of the number and the outputting of the result go in main. Here's an outline
// returns true if the number is a prime, false otherwise
bool prime_check(int a)
{
...
}
// returns true if the number is a reverse prime, false otherwise
bool reverse_prime_check(int a)
{
...
}
int main()
{
int a;
cin >> a;
if (prime_check(a) && reverse_prime_check(a))
cout << "prime\n";
else
cout << "not prime\n";
}
I'll leave you to write the functions themselves, and there's nothing here to do the digit checks either. I'll leave you do to that.
Is there a way to code a recursive function that prints the number of the digits in a number such that:
-It is a void function
-The "if" condition is if(num==0), return
-The "else" will call the recursion.
I saw 2 different types of codes, one of them is where the "if" condition has the recursive call and the else is for "return". But thats not what I want.
I am pretty bad with recursion and trying to understand it by coding myself, but unsuccessfully.
This is my code(I understand why it prints 122 instead of 3 but I dont really know how code it differently. Help anyone?)
#include <iostream>
#include <string.h>
using namespace std;
void numOfDigits(unsigned int num);
int main(){
int num = 994;
numOfDigits(num);
}
void numOfDigits(unsigned int num)
{
int size = 1;
if (num==0)
return;
else
{
if (num / 10 != 0)
size++;
numOfDigits(num / 10);
}
cout << size;
}
A quick hack that makes this code work is to make size static, that is, change
int size = 1;
to
static int size = 1;
But that only works the first time you call the function.
For a more robust solution, in each call to the function you have to pass the count so far:
void numOfDigits(unsigned int num, int countSoFar = 0) {
if (num == 0)
std::cout << countSoFar << '\n';
else
numOfDigits(num / 10, countSoFar + 1);
}
You have a number of mistakes in the numOfDigits() function.
First, you are declaring a new local variable called size each time the function is called. This has no relation to the 'size' defined in the calling function. To see this, print size after initializing it. To fix this, make size static; it will then use the same static variable each time you call the function.
As you are printing size at the end of the function, it simply gives the value of the size variable after that function is run. Even if you set size as static, you will also print the intermediate values of size. An easy way to fix this is to allow the function to return size, and you would have to simply print the value of the function in the main function.
#include <iostream>
#include <string.h>
using namespace std;
int numOfDigits(unsigned int num);
int main(){
int num = 994;
cout<<numOfDigits(num);
}
int numOfDigits(unsigned int num)
{
static int size = 1;
if (num==0)
return 0;
else
{
if (num / 10 != 0)
size++;
numOfDigits(num / 10);
}
return size ;
}
Make sure to put the case with (num == 0) as you want; in this case it prints 0 as the answer.
PS: Always put a space after printing numbers. Otherwise you might think that 1 2 2 (which are the numbers actually printed) is the number 122.
You can pass a value by reference and make use of it, initialize ans=0 every time you call this function
void recursive(unsigned int num,int &ans){
if(num == 0){
return;
}
else{
ans++;
recursive(num/10,ans);
}
}
See this and this
Without using any global variable, this code works. Just a little note: you declared unsigned int the argument, but the number you give to the function is a signed integer.
#include <iostream>
#include <string.h>
using namespace std;
void numOfDigits(unsigned int num, unsigned int& digits);
int main(){
unsigned int num = 93934;
unsigned int digits = 1;
numOfDigits(num, digits);
cout <<digits <<endl;
return 0;
}
void numOfDigits(unsigned int num, unsigned int& digits) {
if (num==0){
return;
}else{
if (num / 10 != 0){
++digits;
numOfDigits(num / 10, digits);
}
}
}
try declaring size globally because it was intialized every time when the funtion executes
int size = 1;
void numOfDigits(unsigned int num)
{
if (num==0)
return;
else
{
if (num / 10 != 0)
size++;
numOfDigits(num / 10);
}
}
print value of size inside main
#include <iostream>
#include <string.h>
using namespace std;
void numOfDigits(unsigned int num);
void main(){
int num = 994;
int size = 1;
cout << numOfDigits(num, size);
}
void numOfDigits(unsigned int num, int &size)
{
if (num==0)
cout<<size;
else
{
if (num / 10 != 0)
size++;
numOfDigits(num / 10, size);
}
}
I think your misunderstanding is that you assume that size is one single variable. However, in every call of your function, you have a different one. Also, every call of your function will print it again.
The cout in your main does nothing, since it prints a void, which has no content.
Usually, you'd give it a return parameter that is the accumulated number, like
int numOfDigits(unsigned int num);
void main(){
cout << numOfDigits(994) << endl;
}
If you don't want that for some reason, you could do it by reference:
int numOfDigits(unsigned int num, unsigned int& digits);
void main(){
unsigned int digits;
numOfDigits(994,digits);
cout << digits << endl;
}
but that is not that good.
That said, in terms of style, what I would do is either making it a loop (idea is that you want to avoid recursion most times):
unsigned int numOfDigits(unsigned int num){
if(num == 0) { return 1; }
unsigned int size = 0;
while(num != 0){
size++;
num /= 10;
}
return size;
}
which can be also done with a call by reference return value. But again, that is somewhat strange if not necessary.
You might even make it a one-liner by using mathematics, cout << floor(log_10(num)) << endl; (not accounting for the special case if num is zero)
One solution that would also work is to make size a global variable. However, I'd advice against that. Global variables should be avoided in general. Just wanted to mention it if somebody else recommends it.
Lastly, you could go with a class, like DigitsCounter that is usually short lived and does the recursive call on methods, with the size variable being a class member. That is overkill in your case, though.
try this code :
int numOfDigits(unsigned int num)
{
int size = 1;
if (num!=0)
{
if (num / 10 != 0)
size+= numOfDigits(num / 10);
}
return size;
}
use the return value in your main function
The problem with using a void return type on recursive functions is that it's not possible for the nested calls to return any information back to the method which invoked them. If we want to print the value at the first (outer) call, that first call can't gain any information from it's recursive call.
As you've observed, it's not possible to simply print the value as we go, since there isn't a one-to-one mapping from recursive calls to characters of the output (if we use Base 10... see the appendix). If we relax the condition that the if condition must return immediately, we can avoid this problem by passing the information as parameters to the recursive call and then printing the value at the deepest level of recursion. For example:
// The accumulator starts at 0, then increases by 1 for each recursive call
void numOfDigits(unsigned int num, unsigned int accumulator = 0) {
if (num == 0) {
if (accumulator == 0) cout << 1; // Special case: numOfDigits(0) = 1
else cout << accumulator;
} else numOfDigits(num / 10, accumulator + 1);
}
Side-note: This is now a tail-recursive method: it makes the recursive call as its last action. This is useful, since it allows the compiler to reduce the space complexity of the method (see explanation). Essentially, the compiler transforms the method to simple iteration, eliminating the need for accumulating stack frames.
Appendix: The only way I can see to keep constraint (2) is to print the number of digits in Base 1, since each digit taken from the argument corresponds directly to a single character in Base 1). This probably isn't what you meant, but here's a solution:
// The accumulator starts at 0, then increases by 1 for each recursive call
void numOfDigits(unsigned int num) {
if (num == 0) return;
else {
cout << 1
numOfDigits(num / 10);
}
}
N.B. This method will not print anything for numOfDigits(0), which is necessary if we want to keep the line if (num == 0) return;
numOfDigits is a void function
The "if" condition is if(num==0), return
The "else" will call the recursion.
Here:
void numOfDigits(unsigned int num) {
if (num == 0)
return;
// The "else" will call the recursion.
else {
static int size = 1;
if (num / 10 != 0) {
size++;
numOfDigits(num / 10);
}
else {
cout << size << '\n';
size = 1;
}
}
}
I am stuck on how to omit trailing zeros, on a recursive call to reverse an integer. If you could just guide me to the right path I'd appreciate it. I am stuck and do not know how to do it. I have came this far, but am struggling to complete it. Thanks.
int main() {
int numToReverse;
cout << "Please enter in a number: " << endl;
cin >> numToReverse;
cout << reverseIntRecursion(numToReverse) << endl;
}
int reverseIntRecursion(int n) {
if (n < 10) //Base Case
return n;
else
cout << n % 10; // Prints out the last number
return reverseIntRecursion(n / 10); // General Case, Recursive Function
}
Maybe easiest way is parse int to string (array of chars) and print as array?
Here is some code that works just fine as long as you enter true for the second parameter:
int ReverseIntRecursion(int, bool);
int main(int argc, const char * argv[]) {
std::cout << ReverseIntRecursion(30400, true);
std::cout << std::endl;
return 0;
}
int ReverseIntRecursion(int N, bool FirstIter)
{
if (N < 10)
return N;
else if (N % 10 == 0 && FirstIter)
return ReverseIntRecursion(N/10, true);
else
std::cout << (N % 10);
return ReverseIntRecursion(N/10, false);
}
// prints 403
Your function isn't reversing an integer. It just prints digits in a reverse order.
This is why you are getting your trailing zeros problem. If you wrote a function which actually reversed the integer - your problem would disappear.
For example:
// Helper function for reversing an integer.
int reverseIntRecursionBase(int n, int& base) {
if (n < 10) // trivial case. If n consists of a single digit - reversed n is equal to n.
{
return n;
}
int result = reverseIntRecursionBase (n/10, base); // recurse until you hit a trivial case.
/*
The leftmost digits in the original number should be the
rightmost digits in the reversed number.
This code will be first executed, after trivial case has been hit:
e.g. given number 1234, this line will be first reached when n = 12; result = 1.
*/
base *= 10;
result = (n % 10)*base + result;
return result;
}
int reverseIntRecursion(int n) {
int base = 1;
return reverseIntRecursionBase (n, base);
}
Live demo.
#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
int prime(int n)
{
int i;
if (n == 1) return 0; // zero- not prime
if (n == 2) return 1; // one- prime
for (i = 2; i <= ceil(sqrt(n)); i++) {
if (n % i == 0) return 0; // remainder is zero
}
return 1;
}
int main()
{
unsigned long n;
while (cin >> n) {
cout << prime(n) << endl;
}
}
I know that 0 means not prime and 1 means prime. Can someone please explain how are all the return functions used to accomplish this?
Why not use cout << "0" for not prime and cout << "1" for prime?
Yes, you could cout directly from the function. That would be valid.
But when you make a mathematical function, it's more conventional to return its value, so that the code that called it can then do whatever it likes. It can cout it, or save it to a variable, or perform other calculations.
If the function directly couted the result, then you're stuck: it can only do that one thing with the result. That's limiting, and for no benefit.
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.