Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Monday, 6 November 2017

java program to print prime numbers

import java.util.Scanner;
public class Prime {
 public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
int no=sc.nextInt(); 
for (int i = 2;i <= no;i++) {
 if (isPrime(i)) {
 System.out.println(i);
 }
 }
 }
 public static boolean isPrime(int num) {
 if (num == 2 || num == 3) {
 return true;
 }
 if (num % 2 == 0|| num % 3 == 0) {
 return false;
 }
 for (int i = 3;i < Math.sqrt(num);i =i+ 2) {
 if (num % i == 0 || num % Math.sqrt(num) == 0) {
 return false;
 }
 }
 return true;
 }
 }

No comments:

Post a Comment