Computer Science Canada My Programs |
Author: | alpesh [ Fri Nov 20, 2009 10:44 pm ] |
Post subject: | My Programs |
/* Example : Input - 153 Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. Armstrong.java */ class Armstrong{ public static void main(String args[]){ int num = Integer.parseInt(args[0]); int n = num; //use to check at last time int check=0,remainder; while(num > 0){ remainder = num % 10; check = check + (int)Math.pow(remainder,3); num = num / 10; } if(check == n) System.out.println(n+" is an Armstrong Number"); else System.out.println(n+" is not a Armstrong Number"); } } |
Author: | alpesh [ Fri Nov 20, 2009 10:46 pm ] |
Post subject: | Re: My Programs |
// The program takes two integer arguments from the command line x and y // and returns the gcd(x,y) class GCDtest { private final static String USAGE = "Usage: java GCDtest x y"; public static void main(String[] args) { // test number of input arguments if (args.length != 2) { System.out.println(USAGE); System.exit(-1); } try { // read in command line input int x = java.lang.Integer.parseInt(args[0]); int y = java.lang.Integer.parseInt(args[1]); // calculate and print gcd recusively System.out.println(gcd(x,y)); } catch (NumberFormatException ex) { System.out.println(USAGE); System.exit(-1); } } // recursive algorithm to calculate the greatest common divisor of two integers private static int gcd(int x, int y) { if (y != 0) return gcd (y, x % y); else return java.lang.Math.abs(x); } } |
Author: | alpesh [ Fri Nov 20, 2009 10:47 pm ] |
Post subject: | Re: My Programs |
/* The program will give the output of Largest of 4 numbers.*/ class Largest4 { public static void main (String args[]) { int a=50,b=3,c=100,d=150; int max; max=(a>b)?(a>c?(a>d?a:d)c>d?c:d))b>c?(b>d?b:d)c>d?c:d)); System.out.println("\n Largest=" +max ); } } |
Author: | wtd [ Sat Nov 21, 2009 1:51 am ] | ||||
Post subject: | Re: My Programs | ||||
alpesh @ Sat Nov 21, 2009 11:47 am wrote:
I challenge you to make this work with any number of integers in an array.
|