0% found this document useful (0 votes)
37 views6 pages

Known Basic Math

Uploaded by

Janvi Waghmode
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views6 pages

Known Basic Math

Uploaded by

Janvi Waghmode
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Known Basic Math

1. Count Digits
2. Problem statement
3. You are given a number ’n’.
4. Find the number of digits of ‘n’ that evenly divide ‘n’.
5. Note:
6. A digit evenly divides ‘n’ if it leaves no remainder when dividing ‘n’.
7. Example:
8. Input: ‘n’ = 336
9. Output: 3

int countDigits(int n){


int count = 0;
int original_n = n;
while (n > 0) {
int lastdigit = n % 10;
if (lastdigit != 0 && original_n % lastdigit == 0) {
count++;
}
n = n / 10;
}
return count;
}
2. Reverse of number

int reverse(int x) {
long ans=0;
while(x)
{
int rem = x%10;
ans = ans*10 + rem;
x/=10;
}
if(ans > INT_MAX || ans < INT_MIN) return 0;
return ans;
}

3. Check Palindrome

bool palindrome(int n){


int rev =0;
while(n>0){
int lastdigit = n% 10;
n = n/10;
rev = rev*10+lastdigit;

}
if(rev==n && n==0)return true;
}

4. Check if a number is Armstrong Number or not

bool checkArmstrong(int n){


int sum =0;
int original_n =n;
while(n>0){
int lastdigit = n%10;
sum = sum+(lastdigit*lastdigit*lastdigit);
n=n/10;
}
return sum == original_n;
}
4. Sum of Divisors of number from 1 to n
Logic:

Code 1:
int sumOfAllDivisors(int n){
int sum=0;
for (int i = 1; i <= n; i++)
{
// Calculating the value of ’sumOfDivisors(i)’ for current 'i'.
for (int j = 1; j<= sqrt(i); j++)
{
if (i % j == 0)
{
// Avoid counting sqrt(i) twice.
if (i / j == j)
{
sum += j;
}
else
{
sum += j + i / j;
}
}
}
}
return sum;
}
Code 2:
long long find(long long n)
{
long long sum = 0;
for (long long i=1;i<=sqrt(n);i++) {
long long t1 = i* (n/i - i + 1);
long long t2 = (((n/i) * (n/i + 1))/2) - ((i*(i+1))/2);
sum += t1 + t2;
}
return sum;
}
int sumOfAllDivisors(int n){
long long sum = find(n);
return sum;
}

5. Prime number

bool isPrime(int n) {
if (n <= 1) {
return false; // 0 and 1 are not prime numbers
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false; // If n is divisible by any number other than 1 and itself, it's not prime
}
}
return true; // If no divisor other than 1 and itself found, n is prime
}

You might also like