- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a number is divisible by all prime divisors of another number in C++
Suppose there are two numbers. We have to check whether a number is divisible by all of the prime factors or the second number or not. Suppose a number is 120. The prime factors are {2, 3, 5}, another number is 75, here the prime factors are {3, 5}. As 120 is divisible by 3 and 5 also, then the decision is yes.
If one number is 1, then it has no prime divisors, so answer is True. Otherwise we have to find the GCD of these two numbers. If GCD is 1, then they are co-prime. So answer is false. If GCD is > 1, then GCD contains prime divisor, which divide x also (x as first number). If we have all unique prime divisor iff second number y / GCD has such unique prime divisor. We have to find uniqueness for pair (x, y/GCD) using recursion.
Example
#include <iostream> #include <algorithm> using namespace std; bool isDivisible(int a, int b) { if (b == 1) return true; int gcd = __gcd(a, b); if (gcd == 1) return false; return isDivisible(a, b / gcd); } int main() { int a = 120, b = 75; if (isDivisible(a, b)) cout << a << " can be divisible by all prime factors of " << b; else cout << a << " can NOT be divisible by all prime factors of " << b; }
Output
120 can be divisible by all prime factors of 75
- Related Articles
- Check if LCM of array elements is divisible by a prime number or not in Python
- Check if a large number is divisible by 20 in C++
- Check if a number is divisible by 23 or not in C++
- Check if a number is divisible by 41 or not in C++
- Check if a number is a power of another number in C++
- Check if a number is Full Prime in C++
- Check if a large number is divisible by 11 or not in C++
- Check if a large number is divisible by 25 or not in C++
- Check if a large number is divisible by 3 or not in C++
- Check if a large number is divisible by 5 or not in C++
- Check if a large number is divisible by 75 or not in C++
- Check if a large number is divisible by 8 or not in C++
- Check if a large number is divisible by 9 or not in C++
- Check if a large number is divisible by 13 or not in C++
- Write a C# program to check if a number is divisible by 2

Advertisements