Find Longest Sequence of Consecutive Composite Numbers in Java
Write a Java program to display the longest sequence of consecutive composite numbers up to N. For example, if N = 10, then the longest sequence of consecutive composite numbers in this range would be 8, 9, 10.
import java.util.Scanner;
class Sequence{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("N = ");
int n = Integer.parseInt(in.nextLine());
int start = 4;
if(n < start){
System.out.println("n should at least be 4!");
return;
}
int count = 0;
int counter = 0;
String s = "";
String seq = "";
for(int i = start; i <= n; i++){
for(int j = i; j <= n; j++){
if(!isPrime(j)){
count++;
if(count == 1)
s += j;
else
s += ", " + j;
}
else
break;
}
if(count > counter){
counter = count;
seq = new String(s);
}
count = 0;
s = "";
}
System.out.println(seq);
}
public static boolean isPrime(int n){
int f = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0)
f++;
}
return f == 2;
}
}
Comments
Post a Comment