TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
magic_number.cpp File Reference

A simple program to check if the given number is a magic number or not. A number is said to be a magic number, if the sum of its digits are calculated till a single digit recursively by adding the sum of the digits after every addition. If the single digit comes out to be 1,then the number is a magic number. More...

#include <cassert>
#include <cstdint>
#include <iostream>
Include dependency graph for magic_number.cpp:

Go to the source code of this file.

Namespaces

namespace  math
 for assert
 

Functions

bool math::magic_number (const uint64_t &n)
 
static void tests ()
 Test function.
 
int main ()
 Main function.
 

Detailed Description

A simple program to check if the given number is a magic number or not. A number is said to be a magic number, if the sum of its digits are calculated till a single digit recursively by adding the sum of the digits after every addition. If the single digit comes out to be 1,then the number is a magic number.

This is a shortcut method to verify Magic Number. On dividing the input by 9, if the remainder is 1 then the number is a magic number else not. The divisibility rule of 9 says that a number is divisible by 9 if the sum of its digits are also divisible by 9. Therefore, if a number is divisible by 9, then, recursively, all the digit sums are also divisible by 9. The final digit sum is always 9. An increase of 1 in the original number will increase the ultimate value by 1, making it 10 and the ultimate sum will be 1, thus verifying that it is a magic number.

Author
Neha Hasija

Definition in file magic_number.cpp.

Function Documentation

◆ main()

int main ( void )

Main function.

Returns
0 on exit

Definition at line 78 of file magic_number.cpp.

78 {
79 tests(); // execute the tests
80 return 0;
81}
static void tests()
Test function.

◆ tests()

static void tests ( )
static

Test function.

Returns
void

Definition at line 52 of file magic_number.cpp.

52 {
53 std::cout << "Test 1:\t n=60\n";
54 assert(math::magic_number(60) == false);
55 std::cout << "passed\n";
56
57 std::cout << "Test 2:\t n=730\n";
58 assert(math::magic_number(730) == true);
59 std::cout << "passed\n";
60
61 std::cout << "Test 3:\t n=0\n";
62 assert(math::magic_number(0) == false);
63 std::cout << "passed\n";
64
65 std::cout << "Test 4:\t n=479001600\n";
66 assert(math::magic_number(479001600) == false);
67 std::cout << "passed\n";
68
69 std::cout << "Test 5:\t n=-35\n";
70 assert(math::magic_number(-35) == false);
71 std::cout << "passed\n";
72}
bool magic_number(const uint64_t &n)