Thursday, 23 February 2012

[C++,PHP] Number Divisibility


[C++,PHP] Number Divisibility

Number Divisibility

Number Divisibility is a check whether your number can be divided by this number or not(must be in whole number, no decimal places allowed).

Example

5 / 2 = 2.5 (False, because its not a whole number)
25 / 5 = 5 (True, because its a whole number)

Snippet

C++

#include <iostream>
using namespace std;
int main()
{
    int num, div_num, num_check;
    cout << "Please enter the number: ";
    cin  >> num;
    cout << "Please enter the number to divide with: ";
    cin  >> div_num;
    num_check = num % div_num;
    if(num_check == 0){
        cout << num << " is a Leap Year" << endl;
    }
    else if(num_check != 0){
        cout << num << " is a Common Year" << endl;
    }
    return 0;
}

PHP

<!DOCTYPE html>
<html lang="en">
<head>
 <title> Number Divisibility </title>
</head>
<body>
 <form action = "<?php htmlentities($_SERVER['PHP_SELF'],ENT_QUOTES); ?>" method = "get">
  Number <input type = "text" name = "num" />
                Number to be divided with <input type = "text" name = "div_num" />
 </form>
</body>
</html>
<?php
    if(isset($_GET['num']) and isset($_GET['div_num'])){
          $num = $_GET['num'];
          $div_num = $_GET['div_num'];
          $num_check = $num % $div_num;
          if($num_check == 0){
               echo htmlentities($num,ENT_QUOTES) . " is divisible by ". $div_num . " <br />";
          }
          else if($num_check != 0){
               echo htmlentities($num,ENT_QUOTES) . " is not divisible by " . $div_num . "<br />";
          }
    }

Explanation

Basically, this code’s major point is at this line:

C++

    num_check = num % div_num;
or

PHP

$num_check = $num % $div_num;

It modulus num with div_num to see whether its divisible or not.
That’s it I suppose, hope you had benefited from my snippet of code.
If you find any bug/suggestions/improvements in my code, please kindly comment at the commentbox and I’ll try to figure it out/update it with the updated version.

0 comments:

Post a Comment