This question already has answers here:
Is there an expression using modulo to do backwards wrap-around ("reverse overflow")?
(6 answers)
Closed 5 years ago.
Given an array of length size and an index n to that array, how can I wrap the index such that it is always within size-1? For positive numbers its simply n % size, but how to achieve backwards wrap around when n is negative?
What I've come up with:
int wrap(int size, int n) {
if (n >= 0)
return n % size;
else
return abs(size + n) % size;
}
But this only works for n <= size; How to make it work for any n?
Expected output:
wrap(4, -1) == 3
wrap(4, -2) == 2
wrap(4, -3) == 1
wrap(4, -4) == 0
wrap(4, -5) == 3
wrap(4, -6) == 2
wrap(4, -7) == 1
wrap(5, -8) == 0
You want the modulo operator with floored division.
int mod_floor(int a, int n) {
return ((a % n) + n) % n;
}
Related
Given integers C and N, (c <= n <= 10^9), find the amount of pairs i,j (n >= i >= j >= 1), where gcd(i,j) == C
long long gcd(long long int a, long long int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
void solve(int tt){
int c,n;
cin >> c >> n;
ll ans = 0;
for(int i = 1; i <= n; i++){
for(int j = i; j <= n; j++){
if(gcd(i,j) == c) ans++;
}
}
cout << ans;
return;
}
This is getting timed out and I've tried various different ways to try and fix it - nothing is working... Does anyone know the code to optimize this? (Output %100000007)
"Given integers C and N, (c <= n <= 10^9), find the amount of pairs i,j (n >= i >= j >= 1), where gcd(i,j) == C"
We can divide everything by C to get:
How many integers i and j satisfy: 2 <= j < i <= n/c, and are relatively prime?
Let's check a few:
n/c count (new pairs listed in parens)
<=2 0
3 1 (2,3)
4 2 (3,4)
5 5 (2,5), (3,5), (4,5)
6 6 (5,6)
7 11 (2,7), (3,7), (4,7), (5,7), (6,7)
8 14 (3,8), (5,8), (7,8)
9 19 (2,9), (4,9), (5,9), (7,9), (8,9)
Each time we increment i, we can pair it with all smaller values of j >= 2 that don't have any of the same factors. For primes this is all smaller values of j >= 2.
This is https://oeis.org/A015613.
Here's an approach courtesy of geeksforgeeks:
Find the count of smaller integers >= 2 relatively prime to n, also known as Euler's totient function, in O(sqrt(n) * log(n)) time as follows:
1) Initialize result as n
2) Consider every number 'p' (where 'p' varies from 2 to Φn).
If p divides n, then do following
a) Subtract all multiples of p from 1 to n [all multiples of p
will have gcd more than 1 (at least p) with n]
b) Update n by repeatedly dividing it by p.
3) If the reduced n is more than 1, then remove all multiples
of n from result.
Add these up for 2 through n in O((n^1.5) * log(n)) time.
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.
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.
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);
}
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'.