prime
A number is said to be a prime number if and only if it is divisible by 1 and the number itself. So in order to check whether a number n is Prime or not Prime we have to check condition till n-1 . To make it simple if the number is 6 then we will check from 2 till 5 and see if it's divisible by any number and if it's not divisible by any number then it is prime. 6 is divisible by 3 so 6 is not a prime. we can just see and tell 6 is not a prime number but we can't do that for numbers>100 or >1000 as fast as compiler does.
a)Java Program to check a given number is prime or not
import java.util.Scanner; public class prime{ public static void main(String args[]){ int flag=0; //Scanner sc=new Scanner(System.in); //int n=sc.nextInt(); //if n is user input int n=127; for(int i=2;i<n;i++){ if(n%i==0){ flag=1; break; } } if(flag==0){ System.out.println("Prime Number"); } else{ System.out.println("Not Prime"); } } }
Output:"Prime Number"
b)Java Program to print prime numbers between a range of numbers
import java.util.Scanner; public class prime{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); for(int i=n;i<=m;i++){ int flag=0; for(int j=2;j<i;j++){ if(i%j==0){ flag=1; } } if(flag==0){ System.out.print(i+" "); } } } }
Output:
3 ---(n entered by user)
20---(m entered by user)
3 5 7 11 13 17 19 --(prime numbers between 3 and 20)
Comments
Post a Comment