3. Amstrong Number

 1. program to print amstrong number in a given range



  // program to print amstrong number in a given range
  import java.util.*;
  import java.util.Scanner;

  public class Amstrong_no
  {
      public static void main(String[] args)
      {
          Scanner sc = new Scanner(System.in);
          int start= sc.nextInt();
          int end = sc.nextInt();
          int rem,temp1,temp2,n,result;


          for (int i=start;i < = end;++i)
          {
              temp1=i;
              temp2=i;
              n=0;
              result=0;
              while(temp1!=0) // to find value of n
              {
                  temp1=temp1/10;
                  ++n;
              }
              while(temp2!=0) // to abc = a*a*a + b*b*b + c*c*c
              {
                  rem=temp2%10;
                  result = result + (int)Math.pow(rem,n);
                  temp2=temp2/10;
              }
              if(result==i) // decides amstrong or not
              {
                  System.out.println(result+" ");
              }

          }
      }
  }
  



2. program to check amstrong or not using while loop.



  // program to check amstrong or not using while loop
  import java.util.*;
  import java.util.Scanner;

  public class Amstrong_or_not
  {
      public static void main(String[] args)
      {
          Scanner sc= new Scanner(System.in);
          int n=sc.nextInt();
          int rem,result=0;
          int temp=n;
          while(temp!=0)
          {
              rem=temp%10;
              result=result+ (int) Math.pow(rem,3);
              temp=temp/10;
          }
          if(result==n)
          {
              System.out.println(n+"\t is a amstrong number");
          }
          else
          {
              System.out.println(n+"\t is not a amstrong number");
          }
      }
  }


2. program to check amstrong or not using for loop.



  // program to check amstrong or not using for loop
  import java.util.*;
  import java.util.Scanner;

  public class Amstrong_or_not
  {
      public static void main(String[] args)
      {
          Scanner sc= new Scanner(System.in);
          int n=sc.nextInt();
          int rem,result=0,i;

          for(i=n;n!=0;n=n/10)
          {
              rem=n%10;
              result=result+ (int) Math.pow(rem,3);
          }
          if(result==i)
          {
              System.out.println(i+"\t is a amstrong number");
          }
          else
          {
              System.out.println(i+"\t is not a amstrong number");
          }
      }
  }

Comments

Popular posts from this blog

Cognizant Tekstac Solutions

BASIC PROGRAMS