Tuesday, February 12, 2019

To find the prime factors of a number

import java.util.*;
class PrimeFactors
{
 
 public static void main()
 {  Scanner sc=new Scanner(System.in);
   int n; int c=0;
   System.out.println("Enter the number");
   n=sc.nextInt();
   System.out.println("Prime factors of "+n);
   for(int i=2;i<=n;i++)
   {
        while (n%i==0)
        {
          for(int j=2;j<=i/2;j++)
          {
            if(i%j==0)
             c++;
            }
            if(c==0)
            {
                System.out.println(i+" ");
                n=n/i;
            }
            c=0;
        }}
    }
}

To check for Goldbach Number

import java.util.*;        //the program is written in Scanner class and with bluej as platform
class goldbach
{
    int prime(int n)
    {    int c=0;
        for(int i=2;i<=n/2;i++)
        {
            if(n%i==0)
                c++;
        }
        if(c==0)                  //prime
            return n;
        else
            return 0;
    }

    public void main()
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the number to check for goldbach");
        int n=sc.nextInt(); int m=0;
        int a[]=new int[n];
        if(n%2==0)
        {
            for(int i=2;i<=n;i++)
            {
                if(prime(i)!=0)
                {
                    a[m]=i;
                    m++;
                }
            }
            for(int i=0;i<m-1;i++)
            {
                for(int j=i;j<m-1;j++)
                {
                    if((a[i]+a[j])==n)
                    {
                        System.out.println(n+"  "+"is a  "+"Goldbach Number");
                        System.exit(0);
                    }
                }
            }
            System.out.println("Not a goldbach number");
        }
        else
        System.out.println("Not an even number");
       
    }
}