Finding and Printing all Prime numbers from 1 to N - java

Here is what I have so far, and I am usually pretty good at tracing programs but i just can't figure out where i got stuck. It's supposed to get "N" and Mod it by D, which equals N-1, while D is greater than 1. And once it is done, it goes on the one number less than the original one, and does the same thing while N is greater than 2. And as for the "Count", i just added it so that I could check if the number was prime. Ex: if the count = N-2, which is basically every number from 2 to N-1, then that number is prime.
public class Challenge14 {
public void inti() {
int count = 0;
int N = 7;
int D = N - 1;
int A = 0;
while (N > 2) {
D = N - 1;
while (D > 1) {
A = N % D;
D--;
if (A == 0) {
break;
}
else {
count++;
}
}
if (count == N - 2) {
System.out.println(N);
}
N--;
}
}
}

Use a for loop.
for (int i = 1; i<N; i++) {
System.out.println(i);
}

Related

How to find divisor of a number that is closest to its square root?

I've been trying to make a program that gives me a divisor of a number n that is closest to its square root.
I've tried to accomplish this by using this program:
public static int closestDivisor(int n) {
for (int i = n/ 2; i >= 2; i--) {
if (n % i == 0) {
return i;
}
}
return 1;
}
However, when I run this:
System.out.println(closestDivisor(42));
I get 21 when expecting either 6 or 7 because those are the closest divisors of 42.
if (i < 4) return 1;
int divisor = 1;
for (int i = 2; i < n; i++) {
if (i * i == n) return i;
if (i * i < n && n % i == 0) divisor = i;
if (i * i > n) return divisor;
}
return -1; // never executed, unreachable
This code should return the largest number which evenly divides n and which is less than or equal to the square root of n.
You can then look at this number, let's call it answer, and n/answer, and one of those is guaranteed to be the factor of n closest to the square root of n. To see which is which, we can compare n - answer*answer and (n/answer * n/answer) - n, and see which is smaller; if the first difference is smaller then answer is closer to n, otherwise n/answer is closer to n.
Here is one way.
First, return -1 if the candidate is < 0 or 1 if < 4
If n is a perfect square, return the square root.
Now inside the loop, Start from the square root and work outwards checking both sides of the square root for divisibility.
The default divisor is initialized to -1.
As the condition is evaluated either i divides n and i is returned via divisor
Otherwise k divides n and k is returned via divisor.
public static int closestDivisor(int n) {
if (n < 4) {
return n < 0 ? -1 : 1;
}
int v = (int)Math.sqrt(n);
int divisor = v;
if (v * v == n) {
return v;
}
for (int i = (int) v, k = i; i >= 1; i--, k++) {
if ( n % (divisor = i) == 0
|| (n % (divisor = k) == 0)) {
break;
}
}
return divisor;
}
public static int closestDivisor(int n) {
int closest = Integer.MAX_VALUE;
int closestDivisor = 1;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (Math.abs(i - n/i) < closest) {
closest = Math.abs(i - n/i);
closestDivisor = i;
}
}
}
return closestDivisor;

Maximum Remainder

Maximum remainder
You are given a number N. Write a program to find a natural number that is smaller than N such that N gives the highest remainder when divided by that number.
If there is more than one such number, print the smallest one.
Can anyone help I think I'm missing something like if 2 numbers will have same reaminders my code would overwrite the minDivisor to the upper value
static int findRemainder(int num){
int maxRemainder=0;
int minDivisor=0
int answer=0;
for(int i = 1; i<num; i++){
if(maxRemainder <= (num % i)) {
maxRemainder = num % i;
if(minDivisor < i && maxRemainder == num%i) {
} else {
minDivisor = i;
}
}
return minDivisor;
}
}
Check this out:
int largestRemainder = c % ((c/2) + 1);

Find Prime Numbers

I am trying to take two arguments from the command line, the first number is the starting point, and the second one is how many prime numbers should be found after that. I need to print the prime numbers found as many times as the second command argument says. I cannot figure out how to make it run the correct amount of times, and after that find the prime number. Here is what I have tried:
int values = Integer.parseInt(args[0]);
int loopAmount = Integer.parseInt(args[1]);
for (int i = 2; i <= loopAmount; i++) {
loopAmount++;
if (values % i != 0) {
values++;
System.out.println(i);
}
}
Your main loop should be something like this:
int start = Integer.parseInt(args[0]);
int count = Integer.parseInt(args[1]);
for (int candidate = start, i = 0; i < count; ++candidate) {
if (isPrime(candidate)) {
i++;
System.out.println(candidate);
}
}
I replaced the variable names to make them more meaningful about their purpose.
Inside the loop, the isPrime method is something you'll have to implement: if the parameter it receives is a prime, return true, otherwise false.
If I understand correctly you want to find N prime numbers starting from X. Code should be pretty simple:
int X = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int C = 0;
while (C < N)
{
for(int i=2; i< X; i++)
{
if(X % i == 0){
X++;
continue;
}
}
System.out.println(X);
X++;
C++;
}
An optimized version :
// cache already found primes
final List<Integer> primes = new ArrayList<>();
/**
* Find {#code count} prime numbers starting at {#code start} inclusive
*/
public void findPrimes(int start, int count) {
for (int i = 2; count > 0; i++) {
if (isPrime(i) && i >= start) {
System.out.println(i);
count--;
}
}
}
private boolean isPrime(final int i) {
int sqrt = (int)Math.sqrt(i);
for (int prime : primes) {
if (i % prime == 0) {
return false;
}
if (prime > sqrt) {
break;
}
}
primes.add(i);
return true;
}
We really need to check for divisors only up to sqrt.
We really need to find only prime divisors since any number can be written as a product of prime numbers.
solution
#include <iostream>
using namespace std;
int main() {
int i, n;
bool isPrime = true;
cout << "Enter a positive integer: ";
cin >> n;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
{
isPrime = false;
}
else
{
//algorithm to check for prime numbers
for (i = 2; i <= n / 2; ++i)
{
if (n % i == 0)
{
isPrime = false;
break;
}
}
}
if (isPrime)
cout << n << " is a prime number";
else
cout << n << " is not a prime number";
return 0;
}

Effective way of find Total number of even divisors of the number

I have to find number of even number of divisor of given number. For this i tried.I am getting correct output but i am getting time complexity more than required.Question :- First line contains the number of testcases T, followed by T lines each containing an integer N output should be - For each testcase, print the required answer in a single line.How can i reduce complexity for this given code.Or can anyone please suggest more efficient way...
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestClass {
public static void main(String args[]) throws Exception {
// Read input from stdin and provide input before running
String frt = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int T = Integer.parseInt(line);
int[] inp = new int[T];
for (int i = 0; i < T; i++) {
int x = Integer.parseInt(br.readLine());
inp[i] = x;
}
int[] ans = new int[T];
int count = 1;
for (int i = 0; i < T; i++) {
int x = inp[i];
if (x % 2 == 0) {
for (int j = 2; j <= x / 2; j = j + 2) {
if (x % j == 0)
count++;
}
} else
count = 0;
ans[i] = count;
}
for (int i = 0; i < T; i++)
System.out.println(ans[i]);
}
}
import java.io.*;
class Ideone
{
public static void main (String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int i,j,k,n;
int[] inp = new int[T];
for (i = 0; i < T; i++) {
inp[i] = Integer.parseInt(br.readLine());
}
//Find all the primes numbers till the square-root of 10^9.
int MAX, root, arrLen;
MAX=1000000000;
arrLen=(int)Math.sqrt(MAX); // arrLen=31622
boolean[] primes=new boolean[arrLen+2]; // No need to find all the primes numbers till MAX
primes[0]=primes[1]=false;
for(i=2;i<arrLen;i++)
primes[i]=true;
// Using Sieve of Eratosthenes
// Square root of 31622 is 177.8
root=(int)Math.sqrt(arrLen); // root=177
for(i=2;i<=root;i++)
{
if(primes[i])
{
n=i*i;
k=0;
//arrLen is the length of primes array.
for(j=n; j<arrLen; k+=1, j=n+(i*k))
primes[j]=false;
}
}
int[] ans = new int[T];
for( i = 0; i < T; i++) {
n = inp[i];
if(n%2==1)
{
ans[i]=0; // Odd numbers will have 0 even divisors
}
else
{
int[] facts=new int[50];
for(k=0;k<50;k++)
facts[k]=1;
facts[0]=0; // fact[0] will contain the highest power of 2 that divides n.
while(n%2==0)
{
facts[0]+=1;
n=n/2;
}
// Prime factorizing n
j=1;
for( k=3; k<arrLen; k+=2)
{
if(primes[k] && n%k==0)
{
while(n%k==0)
{
facts[j]+=1;
n=n/k;
}
j+=1;
}
if(n==1) // To check if n has been completely divided or not.
break;
}
if(n!=1) // To check if there is any prime factor greater than the square root of MAX.
{
facts[j]+=1;
j+=1;
}
int count=1;
for(k=0;k<j;k++)
count=count*facts[k];
ans[i]=count;
}
}
for ( i = 0; i < T; i++)
System.out.println(ans[i]);
}
}
I am of the feeling that this question might have been posted on any competitive coding platform, probably like HackerEarth. If so, then please don't post direct questions on StackOverFlow(in my opinion).
Anyways, I have tested my code and it runs correctly.
In questions where you are not able to reduce time complexity, first make sure that unnecessary objects are not created. Object creation in the memory is a time consuming operation. Avoid irrelevant creation of object and variables. The code above can still be optimized, but that will reduce it's readability. :)
Also before approaching a problem, try to figure out various test cases. Like odd numbers will have 0 even divisors. So by checking whether a number is odd, can reduce several operations.
A bit more explanation to the above code:
Number Of Divisor of A Number are: (N1+1)(N2+1)(N3+1).... Where N1,N2,N3 etc are Powers Of Prime Multiples of the number.
Now if N1 is for 2(the only even prime number),
then Number of Even Divisors of the Number are: N1*(N2+1)*(N3+1)...
In the facts[] array, facts[0] corresponds to N1, while N2, N3 etc are stored in facts[1],facts[2], etc.
facts[0] is initialized with 0, while others are initialized with 1.
The count stores the final product: N1*(N2+1)*(N3+1)... which is equal to the number of Even divisors of the original number.
There is a very simple trick for this,first compute the prime factorization of 720,which is 2^4×3^2×5,the total number of factors here is 3x2×5=30, and number of odd factors (number of factors of the odd primes)=3×2=6,subtracting gives number of even factors = 24.This method works for any number.
NOTE: If the number has no odd factors i.e,the prime factorization is of the form 2a,then the number of number of even factors is a and number of odd factors is 1.
My solution, shorter and simpler:
public class Solution {
public static int numberOfEvenDivisors(int n) {
if (n % 2 == 1)
return 0;
int evenDivisors = 0;
for (int i = 1; i < Math.sqrt(n) + 1; i++) {
if ((i % 2 == 0) && (n % i == 0))
evenDivisors++;
if ((n % (n / i) == 0) && (n / i) % 2 == 0)
evenDivisors++;
if ((i * i == n) && (i % 2 == 0))
evenDivisors--;
}
return evenDivisors;
}
public static void main(String[] args) {
//test here
}
}
Here is short explanation:
When n is odd we return 0, there are no even divisors.
In the first if we check whether i is a divisor and whether i is even. When yes, wo do increment the divisors counter. Note that we start with 1. This is necessary because here we know that n is even and n is its own divisor.
In second if we increment divisors counter if n / i is even and i is a divisor. If i is even, we counted it already in first if. And we know that (n/i) >= i, because we count i only up to square root of n.
And in the last, third if we check the case whether i is a even divisor that is square root of n (for example i == 4, n == 16). Here we decrement number of divisors because we do not want to count same divisor twice. That is.
P.S. We assume n >= 1.
This for loop
for (int i = 0; i < T; i++) {
int x = inp[i];
if (x % 2 == 0) {
for (int j = 2; j <= x / 2; j = j + 2) {
if (x % j == 0)
count++;
} else
count = 0;
ans[i] = count;
}
could be changed to
for (int i = 0; i < T; i+=2) {
int x = inp[i];
for (int j = 2; j <= x / 2; j = j + 2) {
if (x % j == 0)
count++;
if(count != 1)
count = 0;
ans[i] = count;
}
so that it will make the for loop run half as many times.

Find Perfect Number from 1-9999. Exercise from The Art and Science of Java

I am trying to find the perfect number by find out all their divisors. If their sum is equal to the number, then print out the the number. But apparently it's not working.
import acm.program.*;
public class PerfectNumber extends ConsoleProgram{
public void run() {
for (int n = 1; n < 9999; n++) {
for (int d = 2; d < n - 1; d++) {
//d is the potential divisor of n, ranging from 2 to n-1,//
//not including 1 and n because they must be the divisors.//
if (isPerfectNumber(n,d))
print(n );
}
}
}
//method that determines if n is perfect number.//
private boolean isPerfectNumber(int n, int d) {
while (n % d == 0) {
int spd = 1;
spd += d;
if (spd == n) {
return true;
} else {
return false;
}
}
}
}
Looking at the code in your case will return false most of the times. I think what you were looking for is a bit wrong.
Because d is smaller than n, and n divided by d will always be grater than 0. Also in that loop you never change the value of d.
A solution might be:
public void run() {
for (int n = 1; n < 9999; n++)
{ spd=1;
for (int d = 2; d <= n/2; d++) { //no need to go further than n/2
//d is the potential divisor of n, ranging from 2 to n-1,//
if(n%d==0) spd+=d; //if n divides by d add it to spd.
}
if(spd==n) print(n);
}
Try this and let me know if it works for you.
I find something cool here : http://en.wikipedia.org/wiki/List_of_perfect_numbers. You should the much faster using this formula: 2^(p−1) × (2^p − 1). You can see the formula better on the wikilink.
Method isPerfect should probably be something like that:
public static boolean isPerfect(int number) {
int s = 1;
int d = number / 2;
for(int i = 2; i <= d; i++) {
if (number % i == 0) s += i;
}
return s == number;
}

Categories