Coding Interview

coding interview questions part 2

Pinterest LinkedIn Tumblr

is Prime

Prime Number is a number which can be divided evenly only by 1, or itself.
The prime number has only two divisors, 1 and same number. Prime numbers mainly used in public key cryptography.
Example:-
13 We can divide only by 1 or 13. 13 doesn’t have any other divisor. So, it is a prime number.
12 We can divide 1, 2,3,4,6. 12 has many divisors. So, it is not a prime number.

Source Code

package com.dsacode.Probelms;

public class PrimeNumber {

	public static void main(String[] args) {
		int number = 20;
		PrimeNumber oj = new PrimeNumber();
		
		System.out.print("Print the first "+ number +" primenumbers :");
		
		for(int i = 1; i <= number; i++){
			if(oj.isPrime(i))
				System.out.print(i +" ");
		}
	}
	
	public boolean isPrime(int num){
		for(int i=2; i < num; i++){
			
			if(num % i == 0)
				return false;
			
		}
		return true;
	}
	
	
}
#include "stdafx.h"

#include < iostream >
using namespace std;

 bool isPrime(int num){
	for (int i = 2; i < num; i++){

		if (num % i == 0)
			return false;

	}
	return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int number = 20;
	cout << "Print the first " << number << " primenumbers :";
	for (int i = 1; i <= number; i++){
		if (isPrime(i))
			cout << i << " ";
	}
	cout << endl;

	return 0;
}

Output

Print the first 20 primenumbers :1 2 3 5 7 11 13 17 19

Algorithm Explanation

Get the number.
Find module remainder of that number and loop variable from 2 to the maximum of the same number.
If the number with loop value module is zero, then that number is not prime.
Otherwise, the number is a prime number.
1 2 3 4 5

Write A Comment