Java Eratostenes sieve,printing only the biggest prime from a given ceiling? - java

everyone!I have a java app that shows all the prime numbers from 2 to a given number(user input).How can I print out just the last number, the biggest one I mean, from the given range?
For example:if the user input is 12,the compiler prints only 11,not 2,3,5,7,11.
Here is the code:
package sieve_eratos;
import java.util.Scanner;
public class Sieve_Eratos {
public static void main(String[] args) {
// get the ceiling on our prime numbers
int N;
Scanner sc = new Scanner(System.in);
System.out.print("enter the prime number ceiling: ");
N = sc.nextInt();
sc.close();
int k = 0;
// init numbers array, where true denotes primality
boolean[] isPrime = new boolean[N];
// init possible primes
isPrime[0] = false; // 1 is not prime
for (int i = 1; i < N; i++) {
isPrime[i] = true;
k = k + 1;
}
// check every number >= 2 for primality
for (int i = 2; i <= N; i++) {
// i is prime if it hasn't been "crossed off" yet
if (isPrime[i - 1]) {
// print out the prime number
System.out.println(i);
// "cross off" all the subsequent multiples of i
//for (int j = 2*i; j <= N; j += i) {
for (int j = i * i; j <= N; j += i) { // more efficient
isPrime[j - 1] = false;
}
}
}
}
}
I was thinking about creating another integer array and then calling the last element(which will be the last number stored),but I have no idea how to do this.
Thank you in advance!

Use NavigableSet.lower. Take a look at following example
Integer primeValues[]={2,3,5,7,11};//Here store all primes
NavigableSet<Integer> primeCollec=new TreeSet<>();
primeCollec.addAll(Arrays.asList(primeValues));
//Add all range prime into NavigableSet
int input=12;// Get the user input here
int output=primeCollec.lower(input);// Here is the desired output based on input
System.out.println(output);

Since the numbers are consecutive numbers (from 1 to N), we can check the Prime number flags (in your code, it is boolean[] isPrime )from biggest index.
If it is true, then the sum of its index and 1 (index+1) will be the ceiling prime we want.
Code is as follows:
public static int populateCeilingPrime(boolean[] flags)
{
int len = flags.length;
for(int i= len -1;i>=0;i--)
{
if(flags[i])
{
return i+1;
}
}
return 0;
}
so you just need to call this method above to populate the ceiling prime, using the following code at the end of main method.
System.out.printf("The ceiling prime is %d ", populateCeilingPrime(isPrime));

Instead of printing the prime, you could make a check if the number you want to print is larger than some earlier number you wanted to print and then if it is prime, and larger, you save that prime as the biggest so far. Once you are done with your sieveing process, that saved prime should be what you want.
Like so:
int maxPrime = 0;
for (int i = 2; i <= N; i++) {
// i is prime if it hasn't been "crossed off" yet
if (isPrime[i - 1]) {
if(i > maxPrime) {
maxPrime = i;
}
// "cross off" all the subsequent multiples of i
//for (int j = 2*i; j <= N; j += i) {
for (int j = i * i; j <= N; j += i) { // more efficient
isPrime[j - 1] = false;
}
}
}
System.out.println(maxPrime);

Related

I don't know why my code is giving wrong answer

Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
https://leetcode.com/problems/max-consecutive-ones-iii/
This is the question link. On the first test case, I am getting output 9 but it should be 6. I can't figure out where it is going wrong?
public static int f(int arr[],int n,int tar)
{
int st=0,maxc=0,maxf=0;
//tar=tar+1;
for(int i=0;i<n;i++)
{
int se=i-st-maxc;
if(arr[i]==1)
maxc++;
while(i-st-maxc>tar)
{
maxf=Math.max(maxf, i-st);
st++;
}
}
return maxf+1;
}
public static void main(String[] args)
{
Scanner p=new Scanner(System.in);
int n,target;
n=p.nextInt();
target=p.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=p.nextInt();
}
int ans=f(arr,n,target);
System.out.println(ans);
}
You do not need to provide the size of the array because you can get the size from the array.
If you use better variable names, the readability of the code will be better.
Also, you can use if statements in order to check changed values instead of counting.
This is example of the solution:
public static int longestOnes(int[] A, int K) {
var maxCount = 0;
for (int i = 0; i < A.length; i++) {
var count = 0;
var k = 0;
for (int j = i; j < A.length; j++) {
if (A[j] == 1) {
count++;
}
if (A[j] == 0) {
if (k >= K) {
if (count > maxCount) {
maxCount = count;
}
break;
}
count++;
k++;
}
}
}
return maxCount;
}

Cant find the fix for my program at LeetCode Challenge of PrimeNumbers

I have tried several ways changing my code in LeetCode but I can't find the fix, the challenge is the next one :
<<Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.>>
My proposal code is the next one:
import java.util.Scanner;
class Solution {
public int countPrimes(int n) {
Scanner sc = new Scanner(System.in);
int sum = 0;
int cont = 0;
int prime = 0;
prime = sc.nextInt();
int a[] = new int [prime];
for(int i = 0; i < a.length; i++) {
a[i] = i;
cont = 0;
for(int y = 1; y< a.length; y++) {
if(a[i] % y == 0) {
cont ++;
}
}
if (cont == 2) {
sum ++;
}
}
return sum;
}
}
Meanwhile the error marks as follows:
Submission Result: Compile Error More Details
Line 7: error: cannot find symbol [in __Driver__.java] int ret = new Solution().countPrimes(param_1); ^ symbol: method countPrimes(int) location: class Solution
Run Code Status: Runtime Error
×
Run Code Result:
Your input
10
Your answer
java.util.NoSuchElementException
at line 937, java.base/java.util.Scanner.throwFor
at line 1594, java.base/java.util.Scanner.next
at line 2258, java.base/java.util.Scanner.nextInt
at line 2212, java.base/java.util.Scanner.nextInt
at line 8, Solution.countPrimes
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main
Show Diff
Runtime: N/A
Please help!
This'll also pass through:
public class Solution {
public static final int countPrimes(int n) {
// mapping for if the number is divisible by prime numbers, which would make that number a composite number
boolean[] notPrime = new boolean[n];
// counting prime numbers
int count = 0;
for (int i = 2; i < n; i++) {
// If the index of notPrime would be false, we have a prime number, we go through the if, otherwise we continue
if (notPrime[i] == false) {
// Increment the number of prime numbers
count++;
// Look into future numbers
for (int j = 2; i * j < n; j++) {
// find composite numbers and set their indices to true
notPrime[i * j] = true;
}
}
}
return count;
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
Sieve of Eratosthenes
YouTube 1
YouTube 2
You got confused with the input/output part: you don't need any scanner to do this, just:
class Solution
{
public static int countPrimes(int n)
{
int sum = 0;
int a[] = new int [n];
for(int i = 0; i < a.length; i++) {
a[i] = i;
int cont = 0;
for(int y = 1; y< a.length; y++) {
if(a[i] % y == 0) {
cont++;
}
}
if (cont == 2) {
sum++;
}
}
return sum; //this is the output
}
public static void main(String args[])
´{
countPrimes(10); //this is the input
}
}
Proof:
Et voilá. LeetCode accepts the input (10) and the output (4). That's all you need :)
Your answer gets a scanner object which is not needed therefore you could remove it.
You also create an array which will decrease performance, which I recommend not using as you do not need to display the prime numbers but only keep track of them.
public static int countPrimes(int n) {
int sum=0;
for(int i = n; i > 1; i-- ){
int count = 0; //Keep track of the number of primes.
for(int j = 2; j < i; j++){
if(i % j == 0){
count++;
}
}
if(count==0) {
sum++;
}
}
return sum;
}

What would be method to find count which contains only numbers one by one

I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.

How do I let my program print a complete right angle triangle for certain values?

I tested the program out with 88 and it was left with one star to complete the triangle. 87, two stars 86 three stars. This went on for certain numbers.
These are the two options for programming generate function
• One is to compute the length of the last line, say maxLen, and use a double for-loop to generate a line of one star, a line of two stars, a line of three starts, and so on, ending with a line of maxLen stars. The value of maxLen is the smallest integer that is greater than or equal to the
larger solution of the quadratic equation x ( x + 1 ) = 2 * num.
• The other is to use one for-loop to print num stars while executing System.out.println()wherever the newline is needed. The point at which the newline is needed can be computed using two accompanying integer variables, say len and count. Here the former is the length of the line being generated and the count is the number of stars yet to be printed in the line. We start by setting the value of 1 to both integer variables. At each round of the iteration, we decrease the value of count, if the value of count becomes 0, we insert the newline, increase the value of len and then copy of the value of len to count. When the loop terminates, if the value of count is neither equal to 0 nor equal to count, we extend the present line by adding more stars.
import java.util.*;
public class TriangleSingle
{
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x; k++)
{
System.out.print("*");
count --;
if (count == 0)
{
System.out.println();
len ++;
count = len;
}
}
if (count!= 0 || count != len)
{
System.out.println("*"); //Completes the triangle if needed
// This is the **problem spot**
}
Try this:-
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x; k++)
{
for (int i = 1; i <= k; i++) {
System.out.print("*");
}
System.out.println();
}
}
The trick is to increment the count c of printed stars in the inner loop, which prints each row, but check it against the desired number n in the outer loop, which determines how many rows to print. This way we're sure to print complete rows, but we stop as soon as we've printed at least n stars.
public static void generate(int n)
{
for(int c=0, i=0; c<n; i++)
{
for(int j=0; j<=i; j++, c++)
System.out.print('*');
System.out.println();
}
}
Try this out !!!
public class pyramid {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Input Length of pyramid : ");
int length = s.nextInt();
for (int i = 1; i <= length; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*\t");
}
System.out.println("\n");
}
}
Check this out :
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x;)
{
System.out.print("*");
count --;
if (count == 0)
{
System.out.println();
len ++;
k++;
count = len;
}
}

Finding Prime Numbers without using modulus, division, or multiplication

One of the tasks of my homework assignment was to find all prime numbers within a certain length in an array. However, I am having trouble trying to find prime numbers without using modulus or multiplication or division. Any help would be much obliged. The part I'm having difficulty is marked "Testing if it's divisible by other numbers beside 1 and itself."
Here is my code:
class A {
public static void sieve(int [] array) {
//List of primes
int [] primes;
primes = new int[1000000];
//Setting the Array
for(int i = 1; i < array.length; i++) {
array[i] = i;
}
//Finding Primes
System.out.println("Your primes are: ");
for(int j = 0; j < array.length; j++) {
boolean prime = true;
int num = array[j];
//Testing if it's divisible by other numbers beside 1 and itself.
for(int n = 2; n < j; n++) {
num -= n;
if(num == 1) {
prime = false;
}
}
If you need the list of prime number without using modulus, division, or multiplication you have to use Sieve of Eratosthenes.
const int SIZE=100010;
int status[SIZE]={1};
int sieve(){
for(int i=0;i<=SIZE;i++)
status[i]=1;
for(int i=2;i<=SIZE;i++){
if(status[i]==1){
for(int j=2*i;j<=SIZE;j+=i){
status[j]=0;
}
}
}
}
int main(){
sieve();
//check from 2 to 100 which one is prime and which one is not prime
for(int i=2;i<100;i++){
if(status[i]==0)
printf("%d NOT PRIME\n",i);
else if(status[i]==1)
printf("%d PRIME\n",i);
}
}

Categories

Resources