Prime numbers ending with one Program in java

Question:

Write a program that prints a series of prime numbers that end with 1.

Prompt the user for the first number (n1) and the last number(n2) in the series.

Print all possible prime numbers that ends with one from n1 to n2.

If n2 itself is prime, stop the series.  Else print the nearest prime number that ends with one,  next to n2.

Sample input:

Enter the first number

10

Enter the last number

100

Sample output:

11,31,41,61,71,101

CODE:

import java.util.*;


public class Main
{
    public static void main (String[] args) {
        int flag=0, k=0, z=0;
        Scanner sc =new Scanner(System.in );
        System.out.println("Enter the first number");
        int f=sc.nextInt();
        System.out.println("Enter the last number");
        int l=sc.nextInt();
        for(int i=f; i<=l; i++)
        {
            for(int j=2; j<i; j++)// this loop increments flag if i is divisible by j
            {
                if(i%j==0)
                {
                    flag++;
                }
            }
            
            if(i==l && (flag!=0 || i%10!=1))//when last number is not a prime
            {
                while(z==0)
                {
                    for(int a=2; a<i; a++)
                    {
                        if(i%a==0)
                        {
                            flag++;
                        }
                    }
                    
                    if(i%10==1 && flag==0)
                    {
                        System.out.print(","+i);
                        z++;
                    }
                    flag=0;
                    i++;
                }
            }
            
            if(i%10==1 && flag==0)//to check for last digit 1 and prime
            {
                if(k==0)
                {
                    System.out.print(i);  
                    k++;
                }
                
                else
                {    
                    System.out.print(","+i);
                }
            }
            flag=0;
        }
        
    }
}


 Tags:

java interview programs for experienced | java interview programs for freshers pdf | java coding questions for 5 years experience | java programming interview questions – geeksforgeeks |
java programming interview questions and answers for freshers | java programs asked in interview for automation tester | java coding interview questions for experienced professionals
| java coding interview questions pdf | codechef | amazon | microsoft | google | 2021

Previous
Next Post »