Finding Prime Numbers without using modulus, division, or multiplication - java

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);
}
}

Related

Largest number in k swaps

Given a number K and string str of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of str at most K times.
Example 1:
Input:
K = 4
str = "1234567"
Output:
7654321
Explanation:
Three swaps can make the
input 1234567 to 7654321, swapping 1
with 7, 2 with 6 and finally 3 with 5
I am trying to solve it using two loops. For every index i, I am finding the largest integer between (i+1)th index to (N-1)th index, where N is the size of string. If the largest number is greater than arr[i], then swap it. Below is the code I have written.
public static String findMaximumNum(String str, int k) {
int N = str.length();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = Integer.valueOf(str.charAt(i) + "");
}
int swaps = 0;
for (int i = 0; i < N - 1; i++) {
if(swaps == k)
break;
int maxIndex = findMaxInRange(arr, i + 1, N - 1);
if (arr[i] < arr[maxIndex]) {
swap(arr, i, maxIndex);
swaps++;
}
}
String out = "";
for (int i = 0; i < N; i++) {
out = out + arr[i] + "";
}
return out;
}
private static int findMaxInRange(int[] arr, int i, int j) {
int max = Integer.MIN_VALUE;
int maxIndex = i;
for (int k = i; k <= j; k++) {
if (arr[k] >= max) {
max = arr[k];
maxIndex = k;
}
}
return maxIndex;
}
private static void swap(int[] arr, int i, int j) {
System.out.println("swapping "+arr[i]+" and "+arr[j]+" from "+Arrays.toString(arr));
int ch = arr[i];
arr[i] = arr[j];
arr[j] = ch;
}
public static void main(String[] args) {
System.out.println(findMaximumNum("61892795431", 4));
}
It is failing for few test cases. One of the test cases where it is failing is
Input:
4
61892795431
Its Correct output is:
99876215431
And MyCode's output is:
99876125431
I am not able to figure out how the output is '99876215431' and what is wrong in my approach. Please help me understand. Thanks a lot in advance :)
The basic steps how to solve this problem:
0. cast string to array of integers
make a loop K times
in this loop go from i+1 (LOOP VAR) to end of a collection and search for higher value
when we find higher value then collection[i], we will remember its value and index on witch it is. Important thing to note is that we want to swap biggest number but i also has to be last possible number.
at the end of iteration we swap the elements (i with best index)
we are done so all its left is convert our int list back to string.
code: (its python because java is pain)
def sort(swaps, string):
l = list(map(int, list(string)))
print(l)
for i in range(swaps):
best = l[i] + 1
bestIndex = i
for j in range(i+1, len(l)):
if best <= l[j]:
best = l[j]
bestIndex = j
print(i, bestIndex)
l[i], l[bestIndex] = l[bestIndex], l[i]
return "".join(map(str, l))
print(sort(4, "61892795431"))
Your code is correct. The problem comes from the parameter 4 (max number of swaps). If you use 10, the sorting is completed successfully.
Maybe the deeper problems comes from the fact that you are comparing the swaps of your algorithm with the swaps that you would do efficiently to sort the numbers. Your algorithm may work but probably it is not the most efficient, so the number of swaps needed is above the optimum.

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;
}

Count the maximum amount of numbers in an array which sum is an even number

I have this code, which, as I understand it, searches for the maximum amount of consecutive numbers in the given array, which sum is an even number.
private static int f (int[]a, int low, int high)
{
int res = 0;
for (int i=low; i<=high; i++)
res += a[i];
return res;
}
public static int what (int []a)
{
int temp = 0;
for (int i=0; i<a.length; i++)
{
for (int j=i; j<a.length; j++)
{
int c = f(a, i, j);
if (c%2 == 0)
{
if (j-i+1 > temp)
temp = j-i+1;
}
}
}
return temp;
}
For example, the array [-3,4,8,-1,15] should return "4" as and answer, because -3+4+8-1 = 8, and 8 is even.
I need an idea on how to make it more efficient (+what is it's efficiency now? O(n^3)? )
Thanks in advance.
You only need a single loop, which would take O(n).
You need to iterate over the array once and count the number of even numbers and the number of odd numbers. Your output is evenCount + oddCount if oddCount is even, and evenCount + oddCount - 1 otherwise.
The reason for that is that the sum of all even numbers is even. The sum of each pair of odd numbers is also even, so the even sum with the most elements has a number of elements which is either the length of the array (if there's an even number of odd numbers), or the length of the array - 1 (if there's an odd number of odd numbers, in which case you have to exclude one of them from the sum to get an even sum).
Actually, you only have to count the number of odd numbers:
public static int maxEvenSumLength (int []a)
{
int oddCount = 0;
for (int i=0; i<a.length; i++)
{
if (a[i] % 2 == 1) {
oddCount++;
}
}
return (oddCount % 2 == 0) ? a.length : (a.length - 1);
}
EDIT:
I missed the fact that the elements having an even sum should be consecutive. In that case, if the number of odd numbers is even, the result is still the length of the array. The difference is when the number of odd numbers is odd. In that case you should find the odd number closest to either ends of the array, and the length of the consecutive even sum would be the number of elements before the last odd number or after the first odd number (the larger of the two).
public static int maxConsecutiveEvenSumLength (int []a)
{
int oddCount = 0;
int firstOddIndex = -1;
int lastOddIndex = a.length;
for (int i=0; i<a.length; i++)
{
if (a[i] % 2 == 1) {
oddCount++;
if (firstOddIndex < 0)
firstOddIndex = i;
lastOddIndex = i;
}
}
if (oddCount % 2 == 0) {
return a.length;
} else {
return Math.max(a.length - firstOddIndex - 1,lastOddIndex);
}
}
We are still iterating once over the array, so the time complexity is still O(n).

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

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);

Java: Array with loop

I need to create an array with 100 numbers (1-100) and then calculate how much it all will be (1+2+3+4+..+100 = sum).
I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.
I'm thinking something like using variable++ till 100 and then calculate the sum of it all. Not sure how exactly it would be written.
But it's in important that it's in arrays so I can also say later, "How much is array 55" and I can could easily see it.
Here's how:
// Create an array with room for 100 integers
int[] nums = new int[100];
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
nums[i] = i + 1; // +1 since we want 1-100 and not 0-99
// Compute sum
int sum = 0;
for (int n : nums)
sum += n;
// Print the result (5050)
System.out.println(sum);
If all you want to do is calculate the sum of 1,2,3... n then you could use :
int sum = (n * (n + 1)) / 2;
int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
numbers[i] = i+1;
total += i+1;
}
// done
I'm not sure what structure you want your resulting array in, but the following code will do what I think you're asking for:
int sum = 0;
int[] results = new int[100];
for (int i = 0; i < 100; i++) {
sum += (i+1);
results[i] = sum;
}
Gives you an array of the sum at each point in the loop [1, 3, 6, 10...]
To populate the array:
int[] numbers = new int[100];
for (int i = 0; i < 100; i++) {
numbers[i] = i+1;
}
and then to sum it:
int ans = 0;
for (int i = 0; i < numbers.length; i++) {
ans += numbers[i];
}
or in short, if you want the sum from 1 to n:
( n ( n +1) ) / 2
If your array of numbers always is starting with 1 and ending with X then you could use the following formula:
sum = x * (x+1) / 2
from 1 till 100 the sum would be 100 * 101 / 2 = 5050
this is actually the summation of an arithmatic progression with common difference as 1. So this is a special case of sum of natural numbers. Its easy can be done with a single line of code.
int i = 100;
// Implement the fomrulae n*(n+1)/2
int sum = (i*(i+1))/2;
System.out.println(sum);
int[] nums = new int[100];
int sum = 0;
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
{
nums[i] = i + 1;
sum += n;
}
System.out.println(sum);
The Array has declared without intializing the values and if you want to insert values by itterating the loop this code will work.
Public Class Program
{
public static void main(String args[])
{
//Array Intialization
int my[] = new int[6];
for(int i=0;i<=5;i++)
{
//Storing array values in array
my[i]= i;
//Printing array values
System.out.println(my[i]);
}
}
}

Categories

Resources