How to determine, how many number of digits 3 is in variable - c++

I have a variable which contains this numbers
int n = 6396339;
I need to determine how many digits 3 is in variable.
So far i trued like this:
int n = 6396339, counter = 0;
while (n > 0)
{
if ((n % 10) % 3 == 0) {
counter++;
}
n /= 10;
}
cout << counter << endl;
But this algorithm is not working correctly. Could you please help me to solve problem.

(n % 10) % 3 == 0
is true for any digit that is divisible by three, i.e. 0, 3, 6 and 9. Just check whether the digit is equal to 3:
(n % 10) == 3

You could print the number to a string, then traverse the string and check each character whether it is '3'.

Related

Recursive function to counting specific digit

I need to create a recursive function that counts the 2 and 6 from the number a user inputs.
For example if the user enters 26827 the count is 3.
It works with certain numbers and certain numbers it doesn't. Can someone please modify my function making sure its recursive and using very basic C++ language as I have used. Thank you! (I believe something is wrong with return type.)
int count(int n) {
static int count = 0;
if (n == 2 || n == 6) count++;
if ((n % 10 == 2) || (n % 10 == 6)) {
count++;
count(num / 10);
}
else return count;
}
One liner for fun.
int f(int n) {
return n == 0 ? 0 : (n%10==2 || n%10==6) + f(n/10);
}
int count(int n) {
if(n <= 0) return 0; // Base Condition
int countDig = 0; // Initalizing Count of digits
if(n % 10 == 2 || n % 10 == 6) // Checking whether the LSB is 2 or 6
countDig ++; // If it is then incrementing the countDig
countDig += count(n / 10); // Calling the recurive function by sending the number except its LSB
//And incrementing counter according to it
return countDig; // Returning the final count
}
you don't need to have a static value counter. It can be easily done as above. Please refer to comments given. Second the error in your code is you only calling the recursion if the LSB is 2 or 6. The recursion should be put outside the if condition in your code. Why are you using num variable. I think it should be n
You don't need statics
This should work (note return c + count(n / 10) line. That's the main recursion here)
int count(int n)
{
int c = 0;
if(n % 10 == 2 || n % 10 == 6)
c = 1;
if(n < 10)
return c;
return c + count(n / 10);
}
If you want to make it with recursion , another procedure you can apply using string manipulation.
PseudoCode:
Function ( int n):
1. Make n as a string. ( Convert Number to string)
2. Collect the first character (char C) of the string and remove the character from the string.
3. Make the main string again as a number n. ( Convert String to Number).
4. Check the character C , which is number 2 or 6 or not, count it with a flag.
5. Enter base case for which the recursion will stop.
6. return the number n , inside the Function (n) for recursion.

Can someone thoroughly explain this IsItPrime Function?

This is the function I found on CodeReview site, it determines if a number is a prime, while also handling negative numbers. There are few things I can't really catch up with.
1) Why is the first condition <= 3 when it's supposed to deal with negatives?
2) What does return n > 1 actually returns? And does it, in any way, affect other conditions?
bool IsItPrime(int n)
{
if(n <= 3) {
return n > 1;
} else if(n % 2 == 0 || n % 3 == 0) {
return false;
} else {
for(int i(5); i * i <= n; i += 6) {
if(n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
}
if(n <= 3) {
return n > 1;
}
Is clever if not the easiest thing to reason out. First you enter the if body if you have a number of 3 or less. This covers the first 2 prime numbers plus all negative numbers, 0, and 1. Then it goes on to return n > 1; this means that if n is greater than 1 you will return true, otherwise false. So, if n is 2 or 3 the function will return true. It is is less than 2 then it returns false. It would be the same as
if (n <= 1) return false;
else if (n == 2 || n == 3) return true
else if ...
But as you can see that is more typing and adds an if statement.
according to wikipedia:
A prime number (or a prime) is a natural number greater than 1
return n > 1 means return true for any number greater than 1, (i.e. 2 or 3, because this appears after the test if n<=3). 0, 1 or a negative number will make it return false.
1) Why is the first condition <= 3 when it's supposed to deal with
negatives? 2) What does return n > 1 actually returns?
These questions are linked:
The function can take a negative argument, but as you can see the first set of conditions tests if the argument is between 1 and 3. 2,3 being prime, it will return true, if the argument is 1,0 or negative, it will return false (so it doesn't really work with negative numbers).
if(n <= 3) {
return n > 1;
}
This will return false for all numbers less than or equal to 3, except for 2 and 3. This handles negative numbers as well (any negative number will be less than 3).
else if(n % 2 == 0 || n % 3 == 0) {
return false;
}
This does a modulus operation on your argument, and returns false if the number is divisible by 2 or 3 (which would also make it not prime). We're safe to call this even though 2 and 3 are divisible since they're are handled above.
else {
for(int i(5); i * i <= n; i += 6) {
if(n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
This handles all other digits by looping until you're above the square root of a number. It also does modulus operations, this time with 5, 7, and all values n + 6, n + 8 (<11, 13>, <17, 19>, etc). We can iterate by 6 since we're doing the 2 and 3 modulus operations above.

How to add each digit in an integer

This is the question, I have no idea how to do it
(7 points) Write an int function named AddDigit that takes an integer number as input It returns the sum of all digits which are
divisible by 3 or 5. For example,
AddDigit(13579) - it returns 17 (i.e 3+5+9) because 3, 5 and 9 are divisible by 3 or 5
AddDigit(355) - it returns 13 (i.e 3+5+5) because 3 and 5 are divisible by 3 or 5
AddDigit(248) - it returns 0 because no digit is divisible by 3 or 5
And this is my code:
#include <stdio.h>
#include <cstring>
#include<time.h>
#include<iostream>
using namespace std;
int AddDigit(char a[]) {
int sum = 0, numberofdigit;
numberofdigit = strlen(a);
for (int i = 0; i < strlen(a)-1; i++) {
if ((a[i] % 3 == 0 || a[i] % 5 == 0)&&a[i]!=0) {
sum += a[i];
}
}
return sum;
}
int main() {
char b[10];
cin >> b;
cout<<AddDigit(b);
}
You are giving the input as a char array, a character '0' is different from an integer 0,
ASCII of '0' which is 48
ASCII of 0 which is 0
Why you got 50 for '123' because '2' means 50%5==0, so you added '2' to the sum.
To get what u wanted, you need to get the integer equivalent of the char array with d = arr[i]-'0'
int AddDigit(char a[]) {
int sum = 0, numberofdigit;
numberofdigit = strlen(a);
for (int i = 0; i < strlen(a); i++) {
int d = a[i]-'0';
if ((d % 3 == 0 || d % 5 == 0)&&d!=0) {
sum += d;
}
}
return sum;
}
From reading the assignment, the AddDigit function is supposed to take an int argument, not a character array, string, or any other character-based type. Thus your approach starts out incorrectly, since it violates the assignment's requirements.
So the approach is to figure out how to strip each digit from an int, and from that digit, determine if it is evenly divisible by 3 or 5. Using simple modulus and continuous division of the passed-in integer, an approach can be something like this:
int AddDigit(int n)
{
int total = 0; // final total
while (n > 0)
{
int digit = n % 10; // get rightmost digits
// add the value if digit is either evenly divisible by 3 or 5
total += ((digit % 3 == 0 || digit % 5 == 0) ? digit : 0);
// remove the last digit from the number
n /= 10;
}
return total;
}
Note that the line that adds to the total will add 0 if the ternary condition returns false. That condition is to check if either the digit is evenly divisible by 3 or 5. If the condition is true, we simply add that digit onto the total.
It could be a bit more neatly done in a recursive function:
int AddDigit(int num)
{
if (num == 0) //WE REACH THIS WHEN 1-DIGIT NUMBER IS DIVIDED BY 10
return 0;
int curNum = num % 10; //ALWAYS ACCOUNTING FOR ONLY LAST DIGIT
//WE ADD IT OR NOT AND THEN CONTINUE TO THE NEXT DIGIT
if (curNum % 3 == 0 || curNum % 5 == 0)
return curNum + AddDigit(num/10);
else
return AddDigit(num/10);
}

Printing n pairs of prime numbers, C++

I need to write a program which is printing n pairs of prime numbers and the those pairs are :
p q
where p and q are prime numbers and q = p+2.
Input example :
n = 3
3 5 //
5 7 //
11 13 //
I'm pretty much nowhere still... So, someone?
#include <iostream>
#include <cmath>
int twins(int n)
{
for (int i = 0; i < n; i++)
{
???
}
}
int main()
{
std::cout<<twins(5);
return 0;
}
Here is the top-level simple pseudo-code for such a beast:
def printTwinPrimes(count):
currNum = 3
while count > 0:
if isPrime(currNum) and isPrime(currNum + 2):
print currnum, currnum + 2
count = count - 1
currNum = currNum + 2
It simply starts at 3 (since we know 2,4 is impossible as a twin-prime pair because 4 is composite). For each possibility, it checks whether it constitutes a twin-prime pair and prints it if so.
So all you need to do (other than translating that into real code) is to create isPrime(), for which there are countless examples on the net.
For completeness, here's a simple one, by no means the most efficient but adequate for beginners:
def isPrime(num):
if num < 2:
return false
root = 2
while root * root <= num:
if num % root == 0:
return false
root = root + 1
return true
Though you could make that more efficient by using the fact that all primes other than two or three are of the form 6n±1, n >= 1(a):
def isPrime(num):
if num < 2: return false
if num == 2 or num == 3: return true
if num % 2 == 0 or num % 3 == 0: return false
if num % 6 is neither 1 nor 5: return false
root = 5
adder = 2 # initial adder 2, 5 -> 7
while root * root <= num:
if num % root == 0:
return false
root = root + adder # checks 5, 7, 11, 13, 17, 19, ...
adder = 6 - adder # because alternate 2, 4 to give 6n±1
return true
In fact, you can use this divisibility trick to see if an arbitraily large number stored as a string is likely to be a prime. You just have to check if the number below it or above it is divisible by six. If not, the number is definitely not a prime. If so, more (slower) checks will be needed to fully ascertain primality.
A number is divisible by six only if it is divisible by both two and three. It's easy to tell the former, even numbers end with an even digit.
But it's also reasonably easy to tell if it's divisible by three since, in that case, the sum of the individual digits will also be divisible by three. For example, lets' use 31415926535902718281828459.
The sum of all those digits is 118. How do we tell if that's a multiple of three? Why, using exactly the same trick recursively:
118: 1 + 1 + 8 = 10
10: 1 + 0 = 1
Once you're down to a single digit, it'll be 0, 3, 6, or 9 if the original number was a multiple of three. Any other digit means it wasn't (such as in this case).
(a) If you divide any non-negative number by six and the remainder is 0, 2 or 4, then it's even and therefore non-prime (2 is the exception case here):
6n + 0 = 2(3n + 0), an even number.
6n + 2 = 2(3n + 1), an even number.
6n + 4 = 2(3n + 2), an even number.
If the remainder is 3, then it is divisible by 3 and therefore non-prime (3 is the exception case here):
6n + 3 = 3(2n + 1), a multiple of three.
That leaves just the remainders 1 and 5, and those numbers are all of that form 6n±1.
Might not be the most efficient but you can calculate all primes till n, store them in a vector then only print those which have a difference of 2
#include <iostream>
#include<vector>
using namespace std;
void pr(int n, vector<int>& v)
{
for (int i=2; i<n; i++)
{
bool prime=true;
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) v.push_back(i);
}
}
int main()
{
vector<int> v;
pr(50, v);
for(int i = 0;i < v.size()-1; i++) {
if(v[i+1]-v[i] == 2) {
cout << v[i+1] << " " << v[i] << endl;
}
}
return 0;
}
I think is the efficient algo for you and easy to understand. You can change the value of k as per your constraints.
#include <iostream>
#include <cstring>
using namespace std;
int n,p=2,savePrime=2,k=100000;
void printNPrime(int n)
{
bool prime[k];
memset(prime, true, sizeof(prime));
while(n>0)
{
if (prime[p] == true)
{
if(p-savePrime == 2)
{
cout<<savePrime<<" "<<p<<endl;
n--;
}
// Update all multiples of p
for (int i=p*2; i<=k; i += p)
prime[i] = false;
savePrime=p;
}
p++;
}
}
int main() {
cin>>n;
printNPrime(n);
return 0;
}

Is required to only check up to (num/2+1) to determine if a number if prime?

I have successfully coded such a program to complete this task, however my friend and I are currently having a debate over one of the values.
Here is HIS loop function:
for (int iii = 2; iii < (num / 2 + 1); iii++)
{
if (num%iii == 0)
{
return false;
}
}
return true;
My question to him is, "Why do you need "2+1"?" Can't he just use his declared variable "num"?
You only need to check up to sqrt(num), which is less than or equal num/2 for num >= 4. This is because if a number n > sqrt(num) divides num, then num/n < sqrt(num) divides num.
Proof of that claim:
The square root of a positive number n is defined as the unique positive real number x for which x * x == n holds. Now consider you have a divisor d of n such that d > n. Then there is (because d is a divisor) a natural number d2 such that d * d2 == n. It is obvious that d2 := n / d is such a number. From x * x == n, d * d2 == n and d > x one can conclude d2 < x. That means that if a number greater than x divides n, there also is a number less than x that also divides day. So in conclusion, if no number less or equal x divides n, n is prime.
That means the function is correct for all values greater or equal 2. For num >= 4 this follows immediately from the above. For num <= 1 your function will alway return true because the loop never executes. For 2 <= num <=3 the loop returns true correctly because again, the loop is never entered. (Technically, you need the +1 to proof 5 is prime because 5/2=2 < sqrt(5) because of integer division).
Some improvement:
You could test with 2, and avoid all the other even numbers.
You only need to test until sqrt(number), already explained in other answer.
Code:
#include <cmath>
bool is_prime(unsigned long number) {
if (number % 2 == 0 && number != 2)
return false;
unsigned long sqrt_number = static_cast<unsigned long>(std::sqrt(number));
for (unsigned long i = 3; i <= sqrt_number; i += 2) {
if (number % i == 0)
return false;
}
return true;
}
Your code is implementing a "prime number" test. A number is prime if it is not divisible by any whole number other than itself and 1.
This problem space has some well known parameters/factors.
a) The maximum value that any given number, N, can be divided by to produce an integer value is N/2.
b) If N is divisible by an even number, it will also be divisible by 2, i.e. it must be even.
is_prime(N) {
if is_even(N) {
// if N is 2, it's prime, otherwise
// any even number is divisible by
// 2 and thus not prime.
return (N == 2)
}
md = max_divisor(N)
// we've eliminated even numbers, so we need only
// test odd numbers.
// all numbers are divisible by 1, so start at 3.
for (divisor = 3; divisor <= md; divisor += 2) {
// determine whether divisor divides into N
// without remainder indicating non-prime N
remainder = (N % divisor)
if (remainder != 0)
return false
}
return true
}
The max divisor is a number that, when divided into N, will produce 2.
max_divisor * 2 = N ->
max_divisor = N / 2
So simply:
max_divisor(N) return N / 2
What about checking for even numbers? We can do this one of two ways. We can modulo 2, but many people trying to optimize there code will remember their binary logical and realize they just have to test if the lowest bit (bit 1) is set or not.
0001 = 1 (odd)
0010 = 2 (even)
0011 = 3 (odd)
0100 = 4 (even)
0101 = 5 (odd)
0110 = 6 (even)
0111 = 7 (odd)
very simple:
is_even(N) (N % 2) == 0
or
is_even(N) (N & 1) == 0
And converting to C:
static inline bool isEven(unsigned int number) {
return (number & 1) == 0;
}
static inline unsigned int maxDivisor(unsigned int number) {
return (number / 2);
}
unsigned int isPrime(unsigned int number) {
if (isEven(number)) {
// if N is 2, it's prime, otherwise
// any even number is divisible by
// 2 and thus not prime.
// fluffy expanded version
return (number == 2) ? true : false;
// compact version
// return (number == 2);
}
const unsigned int md = maxDivisor(number);
// we've eliminated even numbers, so we need only
// test odd numbers.
// all numbers are divisible by 1, so start at 3.
for (unsigned int divisor = 3; divisor <= md; divisor += 2) {
// determine whether divisor divides into number
// without remainder indicating non-prime number
const unsigned int remainder = (number % divisor);
if (remainder != 0)
return false;
// compact version:
//if (number % divisor)
// return false;
}
return true;
}
Your friend's "(N / 2) + 1" is because he is using a less-than rather than a <=, you could remove the "+1" in his code by writing the following:
for (int iii = 2; iii <= (num / 2); iii++)