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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
|
#include <iostream>
#include <cmath>
using namespace std;
bool isPerfect(int);
bool isPerfectSquare(double);
bool isPrime(int );
bool isTriangular(int);
void counter(int[], bool[], int&, int&, int&, int&, int, int);
void display(int, int, int, int, int, int);
const int MAX = 100001;
struct number_properties
{
int number;
bool prime, perfect, square, triangular;
};
int main()
{
number_properties nums[MAX];
for(int i = 0; i < MAX; i++)
{
nums[i].number = i;
nums[i].prime = isPrime(i);
nums[i].perfect = isPerfect(i);
nums[i].square = isPerfectSquare(i);
nums[i].triangular = isTriangular(i);
}
int prm = 0, prf = 0, tri = 0, sqr = 0;
int start = 1, end = 100000;
bool num[];
counter(nums, num, prm, prf, sqr, tri, start, end);
display(prm, prf, sqr, tri, start, end);
return 0;
}
//This check if a number is perfect
// if it is it will evaluate to true.
bool isPerfect(int n)
{
// To store sum of divisors
long long int sum = 1;
// Find all divisors and add them
for (long long int i=2; i*i<=n; i++)
if (n%i==0)
sum = sum + i + n/i;
// If sum of divisors is equal to
// n, then n is a perfect number
if (sum == n && n != 1)
return true;
return false;
}
//This checks if the number is a
// perfect square, if so it will
//evaluate to true.
bool isPerfectSquare(double num)
{
// Find floating point value of
// square root of num.
long double sr = sqrt(num);
// If square root is an integer
return ((sr - floor(sr)) == 0);
}
//This checks if the number is prime
//if so it will evaluate to true.
bool isPrime(int num)
{
// Corner case
if (num <= 1)
return false;
// Check from 2 to num-1
for (int i = 2; i < num; i++)
if (num % i == 0)
return false;
return true;
}
//This checks if the number is
//triangular if so it will eval to true.
bool isTriangular(int num)
{
// Base case
if (num < 0)
return false;
// A Triangular number must be sum of first n
// natural numbers
int sum = 0;
for (int n = 1; sum<=num; n++)
{
sum = sum + n;
if (sum==num)
return true;
}
return false;
}
void counter(int nums[], bool num[], int& prm, int& prf, int& sqr, int& tri, int start, int end)
{
//int prm = 0, prf = 0, tri = 0, sqr = 0;
for(int j = start; j < end; j++)
{
if (num[j].prime)
prm++;
if (num[j].perfect)
prf++;
if (num[j].square)
sqr++;
if (num[j].triangular)
tri++;
}
}
void display( int prm, int prf, int sqr, int tri, int low, int high)
{
cout<<"Range "<<low<<" to "<<high<<":"<<endl;
cout<<'\t'<<prm<<" Prime numbers"<<endl;
cout<<'\t'<<prf<<" Perfect numbers"<<endl;
cout<<'\t'<<sqr<<" Square numbers"<<endl;
cout<<'\t'<<tri<<" Triangular numbers"<<endl;
}
|