I need to know if a number has a repeating digit using recursion and return 'yes' or 'no'. I am not allowed to use loops or arrays. This is what I've done untill now with 10 global variables and it works, but I think there is a better way.
#include <iostream>
using namespace std;
int counter0 = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
bool check(int k) {
int p = k % 10;;
if (k < 10) {
return false;
} else {
if (p == 0) {
counter0++;
} else if (p == 1) {
counter1++;
} else if (p == 2) {
counter2++;
} else if (p == 3) {
counter3++;
} else if (p == 4) {
counter4++;
} else if (p == 5) {
counter5++;
} else if (p == 6) {
counter6++;
} else if (p == 7) {
counter7++;
} else if (p == 8) {
counter8++;
} else if (p == 9) {
counter9++;
}
if(counter1>1 || counter2>1 || counter3>1 || counter4>1 || counter5>1 || counter6>1 || counter7>1 || counter8>1 || counter9>1)
{
return true;
}
k=k/10;
check(k);
}
}
int main() {
//cout << "Hello, World!" << std::endl;
int n;
cin >> n;
cout << (check(n) ? "yes" : "no") << endl;
//cout << n/10;
return 0;
}
#include <iostream>
using namespace std;
bool hasRepeatingDigit(int n, int mask)
{
// base case: if we have checked all the digits and didn't find any duplicates, return false
if (n == 0)
return false;
/*
p is the place of the last digit in n (n%10).
A digit can range from 0 to 9.
The place of 0 will be 1 << 0 which is 1.
The place of 1 will be 1 << 1 which is 2.
The place of 2 will be 1 << 2 which is 4.
...
...
The place of 9 will be 1 << 9 which is 512.
*/
int p = 1 << (n % 10);
// if place of p has already been marked then it's a duplicate
if (mask&p)
return true;
// otherwise scrap the last digit (n/10), mark place p and recurse on the remaining digits
return hasRepeatingDigit(n / 10, mask|p);
}
int main()
{
int n;
cin >> n;
cout << hasRepeatingDigit(n, 0) << endl;
}
Recursion problems always have a base case and an recursive case.
The base case is simple: k<11 has no repeated digits.
For the recursive case, k has repeated digits if either:
the lower two digits of k are equal, or
k/10 has repeated digits.
So:
bool check(int k) {
if (k < 11)
return false;
int digit = k % 10;
int next = k / 10;
int digit2 = next % 10;
if (digit == digit2)
return true;
else
return check(next);
// Or in one expression:
// return (digit == digit2) || check(next);
}
first, the code is incorrect...
if you enter n=11 it says 'no' but 1 repeated twice. you can fix it by changing the if statement from if(k < 10) to if(k == 0)
you can get down to the bits level but I can't see how much is useful...
in conclusion, this is the best you can do without arrays...
BUT: if you need to find if a digit repeated twice or more in a row the other answer is perfect
Related
The part i am not able to solve is - i am checking the number digits weather they are other than 1 or 0 using the checknumber(). Now, if the digits are other than 0 or 1 then ask the user to enter the num again till the digits are 0 and 1 only. After this, convert into binary and then again check the number is greater than -1 and the number is in negative then only exit. the main function:
int main()
{
int num = 0, flag;
while (num > -1) {
do {
cout << "Enter Number: ";
cin >> num;
} while (checknumber(num, flag) == 0);
cout << "Result in Decimal = ";
cout << binaryToDecimal(num) << endl;
}
}
This is my checknumber():
int checknumber(int number, int flag)
{
while (number != 0) {
int val = number % 10;
if ((val != 1) && (val != 0)) {
flag = 0;
break;
}
else {
flag = 1;
}
return flag;
}
}
the output i am getting when entering the number other than 0 or 1:
In your checknumber function, you're never dividing number, and thus you're stuck in an infinite loop. You're also returning on the first iteration of the loop. I do not understand the usage of flag either.
A corrected checknumber would be:
int checknumber(int number)
{
while(number != 0)
{
int val = number % 10;
if((val != 1) && (val != 0))
{
return 0;
}
number /= 10;
}
return 1;
}
C++ Program help
Hello, I am writing a c++ program to print out several fibonacci numbers that are prime. The program prints out 8 numbers but not only those that are prime. Can some please help me find out what is going on
#include <iostream>
#include <cmath>
using namespace std;
//fibonacci function
int fibonacci(int x) {
if ((x == 1) || (x == 2)) { return 1; }
return fib(x - 1) + fib(x - 2);
}
//prime test bool function
bool is_prime(double n) {
for (int i = 2; i <= sqrt(n); i++) {
if (n % i != 0) { return true; }
else { return false; }
}
}
// main function
int main (){
int y = 1;
int c = 0;
while (y >= 0) {
fibonacci(y);
if ((is_prime(true)) && (fibonacci(y) != 1)) {
cout << fib(y) << " ";
count++;
if (c >= 8) { return 0; }
}
y++;
}
}
return 0;
}
Your code above uses double names for the function, and also you use c while you may mean count.
The is_prime function logic should take an int and the function logic is better to be rewritten to look for values that show if the number is not prime.
Lastly, using recursion with Fibonacci function is resource exhaustive. it is better to use plain loops.
check this code against yours:
#include <iostream>
#include <cmath>
using namespace std;
int fib(int x)
{
int first = 0, second = 1, sum = 0;
if ((x == 1) || (x == 2)) { return 1; }
for (int i = 2; i <= x; ++i)
{
sum = first + second;
first = second;
second = sum;
}
return sum;
}
bool is_prime(int n) // n should be int not double
{
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0)
return false; // you should look for what breaks the condition
return true; // if nothing break the condition you return true
}
int main ()
{
for (int i = 1; i <= 8; ++i)
{
int f = fib(i);
if (is_prime(f))
cout << f << " ";
}
}
Your is_prime() function has a logical problem and appears to be returning the opposite evaluation for input numbers. Try the following:
bool is_prime(int n) {
for (int i=2; i <= sqrt(n); i++) {
// if input divisible by something other than 1 and itself
// then it is NOT prime
if (n % i == 0) {
return false;
}
}
// otherwise it is prime
return true;
}
Here is a demo showing that the refactored is_prime() function is working correctly:
Rextester
Then you can use this function along with your Fibonacci number generator to find say the first 8 prime Fibonacci numbers:
int c = 0;
int y = 1;
do {
int fib = fibonacci(y);
++y;
if (is_prime(fib)) {
cout << fib << " ";
++c;
}
} while (c < 8);
As a side note, your fibonacci() function uses recursion and it won't scale well for large number inputs. Consider using dynamic programming there to dramatically improve performance.
Use Tim Biegeleisen answer for the issues in is_prime() function.
But additionally you do not check your Fibonacci number at all, is_prime is always being called with the same value is_prime(true). And apart of that, in current implementation while cycle will never finish. Try to consider following for the while loop:
while (y >= 0) {
double fib = fibonacci(y);
if ( is_prime(fib) && (fib != 1) ) {
cout << fib << " ";
c++;
if (c >= 8) { return 0; }
}
y++;
}
I've just recently started to dabble in coding, and I ran into a problem that I haven't been able to solve for days, and the closest thing I've been able to find online is a program checking whether a number contains a specific digit, but that doesn't really apply in my case, I don't think. The problem is to let the user enter two positive numbers and check whether the reverse of the second number is contained within the first one. For example if you enter 654321 and 345, it would say say that it contains it because the reverse of 345 is 543 and 654321 contains that. Here's what I've been trying, but it has been a disaster.
P.S: The variables should stay integer through the program.
#include <iostream>
using namespace std;
bool check(int longer, int shorter)
{
int i = 1;
int rev=0;
int digit;
while (shorter > 0)
{
digit = shorter%10;
rev = rev*10 + digit;
shorter = shorter/10;
}
cout << rev << endl;
bool win=0;
int left = longer / 10; //54321
int right = longer % 10; // 65432
int middle = (longer /10)%10; // 5432
int middle1;
int middle2;
int trueorfalse = 0;
while (left > 0 && right > 0 && middle1 > 0 && middle2 >0)
{
left = longer / 10; //4321 //321
right = longer % 10; //6543 //654
middle1 = middle%10; //543
middle2= middle/10; //432
if (rev == left || rev == right || rev == middle1 || rev == middle2 || rev == middle)
{
win = true;
}
else
{
win = false;
}
}
return win;
}
int main ()
{
int longer;
int shorter;
int winorno;
cout << "Please enter two numbers, first of which is longer: ";
cin >> longer;
cin >> shorter;
winorno = check(longer,shorter);
if (winorno==true)
{
cout << "It works.";
}
else
{
cout << "It doesn't work.";
}
return 0;
}
The more you overthink the plumbing, the easier it is to
stop up the drain. -- Scotty, Star Trek III.
This becomes much easier if you divide this task in two parts:
Reverse the digits in an integer.
Search the second integer for the reversed integer calculated by the first part.
For the first part, assume that n contains the number to reverse.
int modulo=1;
int reversed_n=0;
do
{
reversed_n = reversed_n * 10 + (n % 10);
modulo *= 10;
} while ( (n /= 10) != 0);
The end result is if n contained 345, reversed_n will end up with 543, and modulo will be 1000. We'll need modulo for the second part.
The reason the loop is structured this way is intentional. If the original number is 0, we want to wind up with reversed_n also 0, and modulo as 10.
And now, we can take a similar approach to search the second number, called search, whether it contains reversed_n:
for (;;)
{
if ((search % modulo) == reversed_n)
{
std::cout << "Yes" << std::endl;
return 0;
}
if (search < modulo)
break;
search /= 10;
}
std::cout << "No" << std::endl;
Complete program:
#include <iostream>
int main()
{
int search=654321;
int n=345;
int modulo=1;
int reversed_n=0;
do
{
reversed_n = reversed_n * 10 + (n % 10);
modulo *= 10;
} while ( (n /= 10) != 0);
for (;;)
{
if ((search % modulo) == reversed_n)
{
std::cout << "Yes" << std::endl;
return 0;
}
if (search < modulo)
break;
search /= 10;
}
std::cout << "No" << std::endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int calculateNumLength(int num){
int length = 0;
while (num > 0) {
num = num / 10;
length++;
}
return length;
}
bool check(int longer, int shorter){
int reversed = 0;
int digit;
int shortLength = calculateNumLength(shorter);
int longLength = calculateNumLength(longer);
int diffrence = longLength - shortLength;
int possibleValues = diffrence + 1;
int possibleNums[possibleValues];
while ( shorter > 0 ) {
digit = shorter % 10;
rev = ( rev * 10 ) + digit;
shorter = shorter / 10;
}
int backstrip = pow(10, diffrence);
int frontstrip = pow(10, longLength-1);
int arrayCounter = 0;
while ( longer > 0 ){
possibleNums[arrayCounter++] = longer/backstrip;
if ( backstrip >= 10 ){
backstrip = backstrip / 10;
}else{
break;
}
longer = longer % frontstrip;
frontstrip = frontstrip / 10;
}
for (int i=0;i<possibleValues;i++){
if (possibleNums[i] == rev ){
return true;
}
}
return false;
}
int main() {
std::cout << check(654321,123) << std::endl;
return 0;
}
I have this code:
#include <iostream>
#include <cmath>
using namespace std;
int n, liczba;
int main()
{
cin >> n;
for (int i = 0; i < n; i++) {
cin >> liczba;
if (liczba < 2) {
cout << "NIE" << endl;
} else if (liczba == 2) {
cout << "TAK" << endl;
}
for (int i = 2; i < liczba; i++) {
if (liczba % i == 0) {
cout << "NIE" << endl;
break;
} else if (liczba % i != 0) {
cout << "TAK" << endl;
break;
}
}
}
return 0;
}
This program is supposed to write yes "TAK" or no "NIE" whether the number you input is prime or isn't. Variable n is the number of numbers you want to input into program, and liczba is the number you want to check if it's prime or not. It seems to work fine expect one significant thing. If I input number 9 it says yes "TAK" instead of no "NIE".. I discovered that this happens to numbers: 9,27,45,63,81 and so on.. if I add 18 starting from 9 it will happen every time.
What's wrong with my code?
You're breaking on BOTH sides of your if() test. Effectly you'll only ever test one divisor:
e.g. liczba = 9
1. if (liczba % 2 == 0) -> if (9 % 2 == 0) -> if (1 == 0) -> false
2. ...jump to else
3. if (liczba % 2 != 0) -> if (9 % 2 != 0) -> if (1 != 0) -> TRUE
4. spit out 'tak' and break out of the loop
You cannot break out of the loop "early" if you get a remainder. That means the divisor you tested is NOT a factor of the number. You can only break early if you DO get a remainder of 0, which means the number's not prime - it's composite.
Hint:
All prime numbers (except 2 and 3) can be expressed in the form 6k+1
or 6k-1, where k is a positive whole number.
Therefore, This should work:
bool IsPrime( int number )
{
if ( ( (!(number & 1)) && number != 2 ) || (number < 2) || (number % 3 == 0 && number != 3) )
return (false);
for( int k = 1; 36*k*k-12*k < number;++k)
if ( (number % (6*k+1) == 0) || (number % (6*k-1) == 0) )
return (false);
return true;
}
Taken from Determining if a number is prime.
You have not used a flag and thus it says NIE after first check. Also, you are missing an else statement.
Try this instead:
#include <iostream>
#include <cmath>
using namespace std;
int n,liczba;
int main()
{
cin >> n; //
for(int i=0;i<n;i++)
{
cin>>liczba;
if (liczba < 2)
{
cout << "NIE" << endl;
}
else if (liczba == 2)
{
cout << "TAK" << endl;
}
else
{
bool isPrime = true;
for (int i=2;i<liczba;i++)
{
if (liczba % i == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
cout<<"TAK";
else
cout<<"NIE";
}
}
return 0;
}
Currently, if you input 7, It will check if 7 % 2 == 0. Since it is not, it will print "NIE" and break out of the loop.
What is the sum of all the primes below 2000000?
Example of sum below 10 is 2+3+5+7 = 17
I wrote this code, but still getting the wrong answers:
I tested for numbers lower than a few hundreds, and it has shown the correct answers.
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime(long n)
{
if (n < 2)
return false;
if (n == 2)
return true;
if (n == 3)
return true;
int k = 3;
int z = (int)(sqrt(n) + 1); // square root the n, because one of the product must be lower than 6, if squared root of 36
if (n % 2 == 0)
return false;
while (n % k != 0)
{
k += 2;
if (k >= z)
return true;
}
return false;
}
long primeSumBelow(long x)
{
long long total = 0;
for (int i = 0; i < x; i++) // looping for times of prime appearing
{
if (isPrime(i) == true)
total += i;
if (isPrime(i) == false)
total += 0;
}
cout << "fd" << endl;
return total;
}
int main()
{
cout << primeSumBelow(20) << endl;
cout << primeSumBelow(2000000) << endl;
system("pause");
return 0;
}
The total counter's type is correctly long long. Unfortunately the function primeSumBelow returns only long so, depending on the platform, the correctly calculated result is truncated when it's returned from this function.