LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   C - check if a number is divisible by another number (http://www.linuxquestions.org/questions/programming-9/c-check-if-a-number-is-divisible-by-another-number-4175416046/)

Andy Alkaline 07-11-2012 02:27 AM

C - check if a number is divisible by another number
 
A program I threw together recently. It works, but I'm posting it here because I always find it interesting to see comments and suggestions by other users. :)

Code:

/*
 * isdivis.c
 * check if a number is divisible by another number
 *
 * Copyright 2012 Andy Alt
 *        <andyqwerty at users dot sourceforge dot net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>

#define DATE 20120708
#define VER 1

void print_usage(char *argv);

int main(int argc, char **argv)
{
 
  if (argc == 2) {
    if (strcmp (argv[1], "--version") == 0) {
      printf ("isdivis %d-%d\n", VER, DATE);
      exit(0);
    }
    else {
      print_usage(argv[0]);
      exit(1);
    }
  }
 
  if (argc != 3) {
    print_usage(argv[0]);
    exit (2);
  }
 
       
  int dividend = atoi (argv[1]);
  int divisor = atoi (argv[2]);
 
  if ( (dividend > 0 && dividend < INT_MAX)
          && (divisor > 0 && divisor < INT_MAX) ) {
     
    double quotient;
    quotient = ( (double) dividend) / divisor;
   
    if ( ( (int) quotient) == quotient )
      return 0;
    else
      return 1;
  }
  else {
    print_usage(argv[0]);
    exit (2);
  }
     
}

void print_usage(char *argv) {
  printf("usage: %s <dividend> <divisor>\n", argv);
  printf("      %s --version\n\n", argv);
  printf("notes: dividend and divisor must be greater than 0\n");
  printf("      and less than %d\n\n", INT_MAX);
  printf("      If arg1 is divisible by arg2, exit code will be 0\n");
 
}


acid_kewpie 07-11-2012 02:50 AM

Why not just do a modulus? Don't reinvent the wheel.

# echo $((9%3))
0
# echo $((9%4))
1

Andy Alkaline 07-11-2012 03:06 PM

Thanks for pointing out that method. Much better!


All times are GMT -5. The time now is 11:44 AM.