forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhoax_no.cpp
More file actions
87 lines (75 loc) · 2.13 KB
/
hoax_no.cpp
File metadata and controls
87 lines (75 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// CPP code to check if a number is a hoax
// number or not.
#include <bits/stdc++.h>
using namespace std;
// Function to find distinct prime factors
// of given number n
vector<int> primeFactors(int n)
{
vector<int> res;
if (n % 2 == 0) {
while (n % 2 == 0)
n = n / 2;
res.push_back(2);
}
// n is odd at this point, since it is no
// longer divisible by 2. So we can test
// only for the odd numbers, whether they
// are factors of n
for (int i = 3; i <= sqrt(n); i = i + 2) {
// Check if i is prime factor
if (n % i == 0) {
while (n % i == 0)
n = n / i;
res.push_back(i);
}
}
// This condition is to handle the case
// when n is a prime number greater than 2
if (n > 2)
res.push_back(n);
return res;
}
// Function to calculate sum of digits of
// distinct prime factors of given number n
// and sum of digits of number n and compare
// the sums obtained
bool isHoax(int n)
{
// Distinct prime factors of n are being
// stored in vector pf
vector<int> pf = primeFactors(n);
// If n is a prime number, it cannot be a
// hoax number
if (pf[0] == n)
return false;
// Finding sum of digits of distinct prime
// factors of the number n
int all_pf_sum = 0;
for (int i = 0; i < pf.size(); i++) {
// Finding sum of digits in current
// prime factor pf[i].
int pf_sum;
for (pf_sum = 0; pf[i] > 0;
pf_sum += pf[i] % 10, pf[i] /= 10)
;
all_pf_sum += pf_sum;
}
// Finding sum of digits of number n
int sum_n;
for (sum_n = 0; n > 0; sum_n += n % 10,
n /= 10)
;
// Comparing the two calculated sums
return sum_n == all_pf_sum;
}
// Driver Method
int main()
{
int n = 84; //Example input. This number is hoax number.
if (isHoax(n))
cout << "A Hoax Number\n";
else
cout << "Not a Hoax Number\n";
return 0;
}