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);
}
Related
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;
}
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'.
I have a problem with one task, so if you could help me a little bit.
Numbers are "lucky" or "unlucky". Number is "lucky" just if every
digit 7
or every digit is 4. So "lucky" numbers are for example 4, 44, 7, 77.
"Unlucky" are the others numbers.
You will get sequence of n-elements and number K. Your task is to
compute number of all possible k-elements subsequence, which fulfill a one
condition. The condition is that in the subsequence mustn't be two same "lucky"
numbers. So for example there mustn't 77 and 77...
Output number of all possible k-elements subsequence mod 10^9+7
0 < N,K < 10^5
Few examples:
Input:
5 2
7 7 3 7 77
Output:
7
Input:
5 3
3 7 77 7 77
Output:
4
Input:
34 17
14 14 14 ... 14 14 14
Output:
333606206
I have code which seems to work, but it is too slow when I try to compute binomial coefficient. I'm using map. In string I store number in string format. In second - int - part of the map is number which represents how many times was that number(in the first map parameter) used. So now I have stored every "unlucky" numbers stored together. Also every same "lucky" number is together. When I have it stored like this, I just compute all multiplications. For example:
Input
5 2
3 7 7 77 7
Are stored like this: map["other"] = 1 map["7"] = 3 map["77"] = 1
Because k = 2 --> result is: 1*3 + 1*1 + 1*3 = 7.
I think problem is with computing binomial coefficient. For the third example it needs to compute (34 choose 17) and it is computing very long time.I've found this article and also this , but I don't understand how they are solving this problem.
My code:
#include<iostream>
#include<string>
#include<map>
#include <algorithm>
#include <vector>
using namespace std;
int binomialCoeff(int n, int k)
{
// Base Cases
if (k == 0 || k == n)
return 1;
// Recur
return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);
}
int main()
{
int n, k;
cin >> n >> k;
map<string, int> mapa; // create map, string is a number, int represents number of used string-stored numbers ---> so if 7 was used two times, in the map it will be stored like this mapa["7"] == 2 and so on)
for (int i = 0; i < n; i++) // I will load number as string, if this number is "lucky" - digist are all 7 or all 4
{ // every "unlucky" numbers are together, as well as all same "lucky" numbers ---> so 77 and 77 will be stored in one element....
string number;
cin >> number;
char digit = number[0];
bool lucky = false;
if (digit == '7' || digit == '4')
lucky = true;
for (int j = 1; j < number.length(); j++) {
if (digit != '7' && digit != '4')
break;
if (number[j] != digit) {
lucky = false;
break;
}
}
if (lucky)
mapa[number]++;
else
mapa["other"]++;
}
vector<bool> v(mapa.size());
bool lack = k > mapa.size(); //lack of elements in map --> it is when mapa.size() < k; i. e. number of elements in array can't make k-element subsequence.
int rest = lack ? k - mapa.size() + 1 : 1; // how many elements from "unlucky" numbers I must choose, so it makes base for binomial coefficient (n choose rest)
if (lack) //if lack is true, different size of vector
fill(v.begin() + mapa.size(), v.end(), true);
else
fill(v.begin() + k, v.end(), true);
int *array = new int[mapa.size()]; //easier to manipulate with array for me
int sum = 0;
int product = 1;
int index = 0;
for (map<string, int> ::iterator pos = mapa.begin(); pos != mapa.end(); ++pos) // create array from map
{
if (lack && pos->first == "other") { //if lack of elements in map, the number in elemets representing "unlucky" numbers will be binomial coefficient (mapa["other] choose rest)
array[index++] = binomialCoeff(mapa["other"], rest);
continue;
}
array[index++] = pos->second;
}
do { // this will create every posible multiplication for k-elements subsequences
product = 1;
for (int i = 0; i < mapa.size(); ++i) {
if (!v[i]) {
product *= array[i];
}
}
sum += product;
} while (next_permutation(v.begin(), v.end()));
if (mapa["other"] >= k && mapa.size() > 1) { // if number of "unlucky" numbers is bigger than k, we need to compute all possible k-elements subsequences just from "unlucky" number, so binomial coefficient (mapa["other] choose k)
sum += binomialCoeff(mapa["other"], k);
}
cout << sum % 1000000007 << endl;
}
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++)
Write a recursive function to check how many digits in the number can be divided by the digit which is after them. Example: 84963 should return 2, because 8 can be divided by 4 and 6 can be divided by 3. My function doesnt seem to output anything at all.
#include <iostream>
using namespace std;
int fun (int n);
int main()
{
int n;
cin >> n;
cout << fun(n) << endl;
return 0;
}
int fun(int n){
int count = 0;
if (fun(n % 100) % fun(n % 10) == 0)
count++;
return count;
}
Your recursion does not make much sense at the moment. A more logical approach to this would be to see if the last number (so 1 in 321), can currently divide the second last number (so 2 in 321). You could do this by defining a function that checks if that is possible, and recursively passes on the number divided by 10. That function would look something like this:
int fun(int n)
{
if (n < 10)
return 0;
int last = n % 10;
n = n / 10;
int secondlast = n % 10;
if (secondlast != 0 && last != 0 && secondlast % last == 0)
return 1 + fun(n);
else
return fun(n);
}
Update note: After looking into Vlad from moscow's comment, I moved the last != 0 part of the condition forward, to solve a bug (divide by 0).
The problem Vlad from moscow was talking about is the following: If you want, for example, the part 04 to count as 0, you should use the code as it is above. Otherwise you should remove the secondlast != 0 part.
int countIfDiv(int num) {
int pair = num % 100;
int first = pair / 10;
if (first == 0) return 0;
int second = pair % 10;
int next = num / 10;
return first % second == 0 ? 1 + countIfDiv(next) : 0 + countIfDiv(next);
}
Just pull a pair, try the division, then chop the last number and repeat.
You're not actually updating n value so you get into an infinite loop, on the other hand, your function is, initially, only designed for 3 digits number. I think that it should be something similar to:
int fun(int n, int ant, int count){
if( n == 0 )
return count;
if (ant != 0 &&
(n%10) % ant == 0)
count++;
return fun(n/10, n%10, count);
}
I should work with different number of digits.
The valid code will be
size_t fun( int n )
{
const int base = 10;
int digit = n % base;
n /= base;
return ( n == 0 ?
0 :
( digit && n % base && !( n % base % digit ) ) + fun( n ) );
}