program logic of printing the prime numbers - java

Can any body help to understand this java program?
It just prints prime numbers, as you enter how many you want and it works well.
class PrimeNumbers
{
public static void main(String args[])
{
int n, status = 1, num = 3;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of prime numbers you want");
n = in.nextInt();
if (n >= 1)
{
System.out.println("First "+n+" prime numbers are :-");
System.out.println(2);
}
for ( int count = 2 ; count <=n ; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
count++;
}
status = 1;
num++;
}
}
}
I don't understand this for loop condition
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
why we are taking sqrt of num...which is 3....why we assumed it as 3?

Imagine that n can be divided by a number k that is greater than sqrt(n). Then you have:
n = k * j
where j is a number which must be less than sqrt(n) (if both k and j are greater than sqrt(n) then their product would be greater than n).
So you only need to find the divisors that are less than or equals to sqrt(n) and you can find those that are greater than or equals to sqrt(n) by a simple division. In my example, once you have found j, you can find k = n / j.

The line in question is basically trying to find numbers that are factors of your given number (and eliminating them as not-primes). If you find no factors of a given number then you can say that the number is prime.
As far as finding factors goes, you only need to go up to sqrt(N) because if you go any higher you are looking at numbers you have already seen before. This is because every time you find a factor you actually find two factors. If a is a factor of N then N/a and a are both factors of N.

A number N is prime if the only integers that satisfy N = A*B are 1 and N (or N and 1).
Now to check a number N as prime we could search all A from 2 to N and B from 2 to N, to see if N=A*B. That would take O(N^2) time, and is really inefficient.
It turns out that we only need to divide N by a number and see if there is a remainder. This brings it down to O(N).
And further, we don't need to check all the way from A=2 to A=N. If A is greater than sqrt(N), then B must be less than sqrt(N). Therefore we only need to check A from 2 to sqrt(N) to see if N/A has a remainder.

If I'm right there is a theory in math, saying that nearly all prime numbers can be determined when checking numbers from 2 to square root of n instead of checking all numbers from 2 to n oder 2 to n/2.

The factor of a number can lie only from 1 to sqrt of num. So instead of checking from 1 till num for its factors, we check for all numbers from 1 to sqrt(num) so see if any of them divides num. If any divides num, it is not prime, else it is. This improves efficiency of code.

A quick but dirty solution..
import java.util.Scanner;
class testing
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n, i, j, count = 1;
System.out.print("How many Numbers ? : ");
n = input.nextInt();
for(j = 1;count<=n;j++)
{
if(j==1 || j==2)
{
System.out.println(j);
count++;
continue;
}
for(i=2;i<=j/2;i++)
{
if(j%i==0)
break;
else if(i == j/2 && j%i != 0)
{
System.out.println(j);
count++;
}
}
}
}
}

public class PrimeNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList a = new ArrayList();
for (int i = 1; i <= 100; ++i) {
if (isPrime(i))
a.add(i);
}
System.out.println("List : " + a);
}
public static boolean isPrime(int value) {
if (value <= 1)
return false;
if ((value % 2) == 0)
return (value == 2);
for (int i = 3; i <= value - 1; i++) {
if (value % i == 0) {
return false;
}
}
return true;
}
}

Related

Trying to write a program for Highest common factor of two numbers. But the output is showing the initialized value that is 1

The output is not showing the HCF but showing the initialized value that is 1.
package questionsOnLoops;
import java.util.Scanner;
public class hg {
public static void main(String[] args) {
Scanner srv = new Scanner(System.in);
System.out.print("Enter the first number: ");
int n1 = srv.nextInt(); //first number
System.out.println("Enter the second number: ");
int n2 = srv.nextInt(); //second number
int HCF=1; // Highest Common factor
int s; //smaller of two number
s = Math.min(n1, n2);
for(int i = s; i <= 1 ; i--) {
if(n1%i==0&&n2%i==0) {
HCF=i;
break;
}
}
System.out.println(HCF);
}
}
for(i = 1; i <= a || i <= b; i++) {
if( a%i == 0 && b%i == 0 )
hcf = i;
}
Use this logic. here a is the first number and b is the second.
Your code is never executing the "for" loop because you set i=s and i will never be i<=1...
Change to i>=1 and you're good to go
You have just to change your operator in your 'for' loop.
for(int i = s; i >= 1 ; i--) {
Because in your code you loop while i is less than 1. But in your inizialization i is equal to s. So you never enter in the 'for' loop and your HCF is the default value of your HCF variable which is 1.
For your culture if you want an optimized way to calculate the HCF, you can use the Euclidean algorithm which reduce drastically the number of operation. Because you transform several division and condition into a few Euclidean division.
Here an exemple
public int hcf(int m, int n) {
// the remainder of the Euclidean division
int r = 0;
// The algorithm says "the HCF of m and n is the last non-zero remainder"
while(n != 0) {
r = m % n;
m = n;
n = r;
}
return m;
}

Trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20

I'm trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. We are given that 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. My find() finds the number starting from 2520 that is divisible by all numbers from 1-20 but is returning 2520 for some reason. I cannot find what's wrong about my find()?
public class Solution {
public ArrayList<Integer> list = new ArrayList<Integer>();
// creating a list of integers from 1 to 20
public ArrayList<Integer> addtolist() {
for (int i = 1; i <= 20; i++) {
list.add(i);
}
return list;
}
// finds the smallest positive number that is evenly divisible by all
of the numbers from 1 to 20
public int find() {
int num = 2520;
while(true) {
for(int i: list) {
if(num % i == 0) {
return num;
}
else {
num = num + 1;
}
}
}
}
public static void main(String[] args) {
Solution sol = new Solution();
sol.addtolist();
System.out.println(sol.find());//2520
}
}
Your find function returns num if any i in list divides it. It should only return num if every i in num is a divisor.
Although it has to be said that this is far from the most efficient solution to the problem.
You return from the for loop when (num % i == 0), given that i starts at 1 this always true. Instead you need to wait until the end to return:
public int find() {
int num = 2520;
while(true) {
boolean allDivisible = true;
for(int i: list) {
if(num % i != 0) {
allDivisible = false;
break;
}
}
if (allDivisible) {
return num;
else {
num = num + 1;
}
}
}
In your code:
for(int i: list) {
if(num % i == 0) {
return num; // Returns immediately.
}
else {
num = num + 1;
}
}
you return as soon as you find some number in the list that has a match. What you want to do is only return when you have found a value that matches all in the list.
Nice question!
long answer = LongStream.iterate(1, n -> n + 1)
.filter(n -> IntStream.rangeClosed(1, 20).allMatch(f -> n % f == 0))
.findFirst().getAsLong();
Answer is 232792560
There are obviously plenty of shortcuts using math (e.g. only looking at even numbers, ignoring numbers in 1 to 20 that are factors of other numbers in that range).

Decrease execution time of the Java program

I wrote the following program for the second problem of project Euler, for the question: "Project Euler #3: Largest prime factor".It is supposed to print out all the highest prime factors of the provided inputs.
import java.util.Scanner;
public class euler_2 {
public static boolean isPrime(int n) {
if (n % 2 == 0) return false;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int i = 0; i < a; i++) {
int b = sc.nextInt();
for (int j = b; j >= 1; j--) {
boolean aa = isPrime(j);
if (aa == true && b % j == 0) {
b = j;
break;
}
}
System.out.println(b);
}
}
}
What changes can I make to the program to make it execute faster? What would be a better algorithm for this problem?
The problem with your approach is that for every number N, you try each number smaller or equal to N whether it is a prime and after that whether it is a divisor of N.
Obvious improvement is to check whether it is a divisor first and only then whether it is a prime. But most probably this will not help that much.
What you can do instead is just to start checking each number whether it is a divisor of a number. If it is a divisor, divide it. You continue this till sqrt(N).
I have not done anything with java in a long time, but here is Go implementation, which most probably any Java person will be able to transform to Java.
func biggestPrime(n uint64) uint64 {
p, i := uint64(1), uint64(0)
for i = 2; i < uint64(math.Sqrt(float64(n))) + uint64(1); i++ {
for n % i == 0 {
n /= i
p = i
}
}
if n > 1 {
p = n
}
return p
}
Using my algorithm it will take you O(sqrt(N)) to find the biggest prime of a number. In your case it was O(N * sqrt(N))
Attempt to factor the number into 2 factors. Repeat on the largest factor found so far until you find one that can't be factored -- that is the largest prime factor.
There are many different ways you might try to factor the numbers, but since they are only ints, then Fermat's method or even trial division (going down from sqrt(N)) will probably do. See http://mathworld.wolfram.com/FermatsFactorizationMethod.html

In Java how to find random factors of a given number

I have a given number. How can I find the factors of that number (for example, 5 and 3 for the number 15)? Here is the code I tried:
int factor1 = 2;
while ((a % factor1 != 0) && (a >= factor1)) {
d++;
}
if (factor1 == a){
d = 1;
}
But this gives me only the smallest factor (i.e a=3 all the time). I would like to get a random set of factors.
Loop through each number from 1 to N inclusively using the modulus operator (%). If n%currentNumber==0, they are a factor. Below, I did this using a for loop, outputting each factor as it is found.
int number=15;
for(int i = 1; i <= number; i++){
if(number%i==0){
System.out.println("Found factor: " + i);
}
}
As Theo said in a comment on this post, you can also use number/2, and arbitrarily include 1 and number.
int number=2229348;
System.out.println("Found factor: " + 1);
for(int i = 2; i <= number/2; i++){
if(number%i==0){
System.out.println("Found factor: " + i);
}
}
System.out.println("Found factor: " + number);
You can iterate through the numbers from 2 to a/2 and check if the given number divides a, which is done using the % operator:
int a = 15;
System.out.print("Divisors of " + a + ": ");
for(int i = 2; i <= a/2; ++i) {
if(a % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
This code prints all of the divisors of a. Not that you most probably want to ignore 1, since it divides all integers. Moreover, you don't need to check the numbers until a, because no number bigger than a / 2 can actually divide a apart from a itself.
The while loop with default values of a=15 and multiple=2 is already in an infinite loop. You need to correct that and check for subsequent increments of multiple whenever a%multiple ! = 0
public class Factors {
public static void main(String[] args){
/**
int multiple1=2,d=0,a=15; //multiple to be rephrased as factor
while((a%multiple1 != 0)&&(a>=multiple1)){
multiple1++; //this will increment the factor and check till the number itself
//System.out.println(multiple1+" is not a factor of a");
}
if(multiple1==a){
d=1;
}
*commented the original code
*/
int factor=1,d=0,a=20; //multiple rephrased as factor
while(a/2>=factor){ //re-arranged your while condition
factor++;
if((a%factor==0))
d++; //increment factor count whenever a factor is found
}
System.out.println("Total number of factors of a : "+(d+2)); // 1 and 'a' are by default factors of number 'a'
}
}
To find all factors inlcuding 1 and the number itself you can do something like below:
//Iterate from 2 until n/2 (inclusive) and divide n by each number.
//Return numbers that are factors (i.e. remainder = 0). Add the number itself in the end.
int[] findAllFactors(int number) {
int[] factors = IntStream.range(1, 1 + number / 2).filter(factor -> number % factor == 0).toArray();
int[] allFactors = new int[factors.length+1];
System.arraycopy(factors,0,allFactors,0,factors.length);
allFactors[factors.length] = number;
return allFactors;
}
To find only prime factors you can do something like this:
//Iterate from 2 until n/2 (inclusive) and divide n by each number.
// Return numbers that are factors (i.e. remainder = 0) and are prime
int[] findPrimeFactors(int number) {
return IntStream.range(2, 1 + number/ 2).filter(factor -> number % factor == 0 && isPrime(factor)).toArray();
}
Helper method for primality check:
//Iterate from 2 until n/2 (inclusive) and divide n by each number. Return false if at least one divisor is found
boolean isPrime(int n) {
if (n <= 1) throw new RuntimeException("Invalid input");
return !IntStream.range(2, 1+n/2).filter(x -> ((n % x == 0) && (x != n))).findFirst().isPresent();
}
If you are not on Java 8 and/or not using Lambda expressions, a simple iterative loop can be as below:
//Find all factors of a number
public Set<Integer> findFactors(int number) {
Set<Integer> factors = new TreeSet<>();
int i = 1;
factors.add(i);
while (i++ < 1 + number / 2) {
if ((number % i) == 0) {
factors.add(i);
}
}
factors.add(number);
return factors;
}
public class Abc{
public static void main(String...args){
if(args.length<2){
System.out.println("Usage : java Abc 22 3");
System.exit(1);
}
int no1=Integer.parseInt(args[0]);
int no=Integer.parseInt(args[1]),temp=0,i;
for(i=no;i<=no1;i+=no){
temp++;
}
System.out.println("Multiple of "+no+" to get "+no1+" is :--> "+temp);
//System.out.println(i+"--"+no1+"---"+no);
System.out.println("Reminder is "+(no1-i+no));
}
}

How does this prime number test in Java work?

The code snippet below checks whether a given number is a prime number. Can someone explain to me why this works? This code was on a study guide given to us for a Java exam.
public static void main(String[] args)
{
int j = 2;
int result = 0;
int number = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = reader.nextInt();
while (j <= number / 2)
{
if (number % j == 0)
{
result = 1;
}
j++;
}
if (result == 1)
{
System.out.println("Number: " + number + " is Not Prime.");
}
else
{
System.out.println("Number: " + number + " is Prime. ");
}
}
Overall theory
The condition if (number % j == 0) asks if number is exactly divisible by j
The definition of a prime is
a number divisible by only itself and 1
so if you test all numbers between 2 and number, and none of them are exactly divisible then it is a prime, otherwise it is not.
Of course you don't actually have to go all way to the number, because number cannot be exactly divisible by anything above half number.
Specific sections
While loop
This section runs through values of increasing j, if we pretend that number = 12 then it will run through j = 2,3,4,5,6
int j = 2;
.....
while (j <= number / 2)
{
........
j++;
}
If statement
This section sets result to 1, if at any point number is exactly divisible by j. result is never reset to 0 once it has been set to 1.
......
if (number % j == 0)
{
result = 1;
}
.....
Further improvements
Of course you can improve that even more because you actually need go no higher than sqrt(number) but this snippet has decided not to do that; the reason you need go no higher is because if (for example) 40 is exactly divisible by 4 it is 4*10, you don't need to test for both 4 and 10. And of those pairs one will always be below sqrt(number).
It's also worth noting that they appear to have intended to use result as a boolean, but actually used integers 0 and 1 to represent true and false instead. This is not good practice.
I've tried to comment each line to explain the processes going on, hope it helps!
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
It works by iterating over all number between 2 and half of the number entered (since any number greater than the input/2 (but less than the input) would yield a fraction). If the number input divided by j yields a 0 remainder (if (number % j == 0)) then the number input is divisible by a number other than 1 or itself. In this case result is set to 1 and the number is not a prime number.
Java java.math.BigInteger class contains a method isProbablePrime(int certainty) to check the primality of a number.
isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime.
For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.
Miller–Rabin primality algorithm is used to check primality in this method.
import java.math.BigInteger;
public class TestPrime {
public static void main(String[] args) {
int number = 83;
boolean isPrime = testPrime(number);
System.out.println(number + " is prime : " + isPrime);
}
/**
* method to test primality
* #param number
* #return boolean
*/
private static boolean testPrime(int number) {
BigInteger bValue = BigInteger.valueOf(number);
/**
* isProbablePrime method used to check primality.
* */
boolean result = bValue.isProbablePrime(1);
return result;
}
}
Output: 83 is prime : true
For more information, see my blog.
Do try
public class PalindromePrime {
private static int g ,k ,n =0,i,m ;
static String b ="";
private static Scanner scanner = new Scanner( System.in );
public static void main(String [] args) throws IOException {
System.out.print(" Please Inter Data : ");
g = scanner.nextInt();
System.out.print(" Please Inter Data 2 : ");
m = scanner.nextInt();
count(g,m);
}
//
//********************************************************************************
private static int count(int L, int R)
for( i= L ; i<= R ;i++){
int count = 0 ;
for( n = i ; n >=1 ;n -- ){
if(i%n==0){
count = count + 1 ;
}
}
if(count == 2)
{
b = b +i + "" ;
}
}
System.out.print(" Data : ");
System.out.print(" Data : \n " +b );
return R;
}
}

Categories