"for" loop and perfect numbers [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Have to create program that list all perfect number( sum of factors = number ) 1 - 1000.
this is for a java class, need to only use "for" loops
I have checked my code 100 times and getting no output, I am missing a logical error somewhere, could someone help me out?
public static void main(String[] args)
{
// variables
int total = 0;
final int LIMIT = 1000;
// for loop to test all numbers 1-1000
for(int i = 1; i <= LIMIT; i++)
{
// if statement
if((i != 1) && (total == i - 1))
{
// prints perfect number
System.out.println((i - 1) + " is a perfect number");
// resets total value
total = 0;
}
// gets and add factors as total
for(int divider = 1; divider < i; divider++)
{
if((i % divider) == 0)
{
total += divider;
}
}
}
}

Your big problem is that you only reset total if you find a perfect number. If you don't find a perfect number, you continue adding divisors for the next number to the old total. You need to start fresh for every i.
Rearranging your program in the following way should help:
public static void main(String[] args) {
final int LIMIT = 1000;
for (int i = 0; i <= LIMIT; i++) {
// Declare total here, inside the loop, so values from previous
// iterations are discarded.
int total = 0;
for (/* your code here */) {
// add up divisors
// your code here
}
// compare to i, rather than always computing the total for the
// previous number and comparing to that.
if (/* your code here */) {
// print output
// your code here
}
}
}

You should move total = 0; outside of your if statement. Your total is adding up and never being reset.

I reccomend to split your algorithm to different parts, so you can focus on smaller tasks at time.
Find factors of number i. A method that gets a number and return an arrays of it's factors.
Sum factors together. A simple method that takes an array and returns it's the sum.
Main loop: just check if sum(factors(i)) == i
You can start with the more easy ones (Hint: 2 and 3) and then maybe search for some not-totally-inefficient ways to implement 1

(total == i - 1) will never match when you start with total=0 and i>1.

You were close. Just need to re-evaluate your logic a bit.
public static void main(String[] args) {
// variables
int total = 0;
final int LIMIT = 1000;
// for loop to test all numbers 1-1000
for (int i = 1; i <= LIMIT; i++) {
// gets and add factors first
for (int divider = 1; divider < i; divider++) {
if ((i % divider) == 0) {
total += divider;
}
}
// then check if sum == number
// also just print i instead of - 1
if ((i != 1) && (total == i)) {
// prints perfect number
System.out.println((i) + " is a perfect number");
}
// alway reset when we are done with a number
total = 0;
}
}

for(int i=1;i<1000;i++)
{
int k=0;
for(int j=1;j<i;j++)
{
if(i % j==0)
{
k+=j;
}
}
if(k==i)
{
System.out.println(k);
}
}

Related

Formatting returned Strings?

I'm really new to coding and just got assigned my first coding homework involving methods and returns. I managed to struggle through and end up with this, which I'm pretty proud of, but I'm not quite sure it's right. Along with that, my return statements are all on the same lines instead of formatted how my teacher says they should be ("n is a perfect number", then the line below says "factors: x y z", repeated for each perfect number. Below are the exact instructions plus what it outputs. Anything will help!
Write a method (also known as functions in C++) named isPerfect that takes in one parameter named number, and return a String containing the factors for the number that totals up to the number if the number is a perfect number. If the number is not a perfect number, have the method return a null string (do this with a simple: return null; statement).
Utilize this isPerfect method in a program that prompts the user for a maximum integer, so the program can display all perfect numbers from 2 to the maximum integer
286 is perfect.Factors: 1 2 3 1 2 4 7 14
It should be
6 is perfect
Factors: 1 2 3
28 is perfect
Factors: 1 2 4 7 14
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in) ;
System.out.print("Enter max number: ") ;
int max = input.nextInt() ;
String result = isPerfect(max) ;
System.out.print(result) ;
}
public static String isPerfect(int number) {
String factors = "Factors: " ;
String perfect = " is perfect." ;
for (int test = 1; number >= test; test++) {
int sum = 0 ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
sum += counter ;
}
}
if (sum == test) {
perfect = test + perfect ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
factors += counter + " " ;
}
}
}
}
return perfect + factors ;
}
}
Couple of things you could do:
Firstly, you do not need two loops to do this. You can run one loop till number and keep checking if it's divisible by the iterating variable. If it is, then add it to a variable called sum.
Example:
.
factors = []; //this can be a new array or string, choice is yours
sum=0;
for(int i=1; i<number; i++){
if(number % i == 0){
sum += i;
add the value i to factors variable.
}
}
after this loop completes, check if sum == number, the if block to return the output with factors, and else block to return the output without factors or factors = null(like in the problem statement)
In your return answer add a newline character between perfect and the factors to make it look like the teacher's output.
You can try the solution below:
public String isPerfect(int number) {
StringBuilder factors = new StringBuilder("Factors: ");
StringBuilder perfect = new StringBuilder(" is perfect.");
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
factors.append(" " + i);
}
}
if (sum == number) {
return number + "" + perfect.append(" \n" + factors);
}
return number + " is not perfect";
}
Keep separate variables for your template bits for the output and the actual output that you are constructing. So I suggest that you don’t alter factors and perfect and instead declare one more variable:
String result = "";
Now when you’ve found a perfect number, add to the result like this:
result += test + perfect + '\n' + factors;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
result += counter + " ";
}
}
result += '\n';
I have also inserted some line breaks, '\n'. Then of course return the result from your method:
return result;
With these changes your method returns:
6 is perfect.
Factors: 1 2 3
28 is perfect.
Factors: 1 2 4 7 14
Other tips
While your program gives the correct output, your method doesn’t follow the specs in the assignment. It was supposed to check only one number for perfectness. Only your main program should iterate over numbers to find all perfect numbers up to the max.
You’ve got your condition turned in an unusual way here, which makes it hard for me to read:
for (int test = 1; number >= test; test++) {
Prefer
for (int test = 1; test <= number; test++) {
For building strings piecewise learn to use a StringBuffer or StringBuilder.
Link
Java StringBuilder class on Javapoint Tutorials, with examples.

Trying to Solve Project's Euler's First Questions Using Java, Am Having Trouble Returning the Result

I am trying to make a program that solves Project Euler's First Problem. However I am having trouble returning my sum.
To approach this problem, I am trying to first add up all of the multiples of three and assigning that value of the added multiples to the integer sum. Then I am trying to do the same with the multiples of five accordingly.
Finally I am trying to add the two sums together, the sum of the three multiples and the sum of the five multiples, and them printing out the coalesced value of the two sums via the last sum.
This is the Java code I am trying to use to achieve this.
public class Main {
public static void main(String[] args) {
int sum = 0;
int t = 3;
while (sum < 1000) {
if (sum % 3 == 0)
sum += t;
}
int sum2 = 0;
int f = 5;
while (sum2 < 1000) {
if (sum % 5 == 0)
sum += f;
}
int sum3 = sum + sum2;
System.out.println(sum3);
}
}
I did get one error saying sum2 < 1000 is always true. However, I do not understand how to fix this problem.
Any help is utterly appreciated.
check the comments, hope it helped.
public static void main(String []args){
int sum = 0; //store all the numbers
int t = 3; // the starting point (it can be 3 if you want)
while (t < 1000) { // as long t is lower than 1000
if ( t % 3 == 0 || t % 5 == 0) { //check if t is divided by 3 or 5
sum += t; //add to sum
}
t++; //add 1 to t (t will increase and eventualy be bigger than 1000)
}
System.out.println(sum); //print sum
}

Java program taking forever to run with large numbers

I am writing a Java program that calculates the largest prime factor of a large number. But I have an issue with the program's complexity, I don't know what has caused the program to run forever for large numbers, it works fine with small numbers.
I have proceeded as follow :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Largest_prime_factor {
public static void main(String[] args)
{
//ArrayList primesArray = new ArrayList();
ArrayList factorArray = new ArrayList();
long largest = 1;
long number = 600851475143L ;
long i, j, k;
//the array list factorArray will have all factors of number
for (i = 2; i < number; i++)
{
if( number % i == 0)
{
factorArray.add(i);
}
}
Here, the Array List will have all the factors of the number.
So I'll need to get only the prime ones, for that, I used a method that checks if a number is prime or not, if it's not a prime number, I remove it from the list using the following method :
java.util.ArrayList.remove()
So the next part of the code is as follow :
for (i = 2; i < number; i++)
{
if (!isPrime(i))
{
factorArray.remove(i);
System.out.println(factorArray);
}
}
System.out.println(Collections.max(factorArray));
}
The last line prints the largest number of factorArray, which is what I am looking for.
public static boolean isPrime(long n)
{
if(n > 2 && (n & 1) == 0)
return false;
for(int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
}
The function above is what I used to determine if the number is a prime or not before removing it from the list.
This program works perfectly for small numbers, but it takes forever to give an output for large numbers, although the last function is pretty fast.
At first, I used to check if a number is prime or not inside of the first loop, but it was even slower.
You are looping over 600851475143 numbers.
long number = 600851475143L ;
for (i = 2; i < number; i++)
Even if we assume that each iteration takes very very small time (as small as 1 microsecond), it'll still take days before the loop finishes.
You need to optimise your prime-finding logic in order for this program to run faster.
One way to reduce the iterations to reasonable number is to loop until square root of number.
for (i = 2; i < Math.sqrt(number); i++)
or
for (i = 2; i*i < number; i++)
The calculation of the prime factors of 600851475143L should take less than a milli-second (with a not totally inefficient algorithm). The main parts your code is currently missing:
The border should be sqrt(number) and not number.
The current value should be checked in a while-loop (to prevent that non-prime-factors are added to the list, reduces range to check).
The max. value should be decreased (as well as the border) to number/factor after finding a factor.
Further improvements are possible, e.g. to iterate only over non-even numbers (or only iterate over numbers that are neither a multiple of 2 and 3) etc.
An example implementation for the same question on codereview (link):
public static long largestPrimeFactor(
final long input) {
////
if (input < 2)
throw new IllegalArgumentException();
long n = input;
long last = 0;
for (; (n & 1) == 0; n >>= 1)
last = 2;
for (; n % 3 == 0; n /= 3)
last = 3;
for (long v = 5, add = 2, border = (long) Math.sqrt(n); v <= border; v += add, add ^= 6)
while (n % v == 0)
border = (long) Math.sqrt(n /= last = v);
return n == 1 ? last : n;
}
for (i = 2; i < number; i++)
{
if( number % i == 0)
{
factorArray.add(i);
}
}
For an large input size, you will be visiting up to the value of the number. Same for the loop of removing factors.
long number = 600851475143L ;
this is a huge number, and you're looping through this twice. Try putting in a count for every 10,000 or 100,000 (if i%10000 print(i)) and you'll get an idea of how fast it's moving.
One of the possible solutions is to only test if the the prime numbers smaller than the large number divide it.
So I checked
for (i=2; i < number; i++)
{
if(isPrime(i))
{
if( number % i == 0)
{
factorArray.add(i);
}
}
}
So here I'll only be dividing by prime numbers instead of dividing by all numbers smaller than 600851475143.
But this is still not fast, a complete modification of the algorithm is necessary to obtain an optimal one.
#Balkrishna Rawool suggestion is the right way to go. For that I would suggest to change the iteration like this: for (i = 3; i < Math.sqrt(number); i+=2) and handle the 2 manually. That will decrease your looping because none of the even numbers except 2 are prime.

Calculating Perfect Numbers

See, I have a boolean method that gets the divisors that work by moding the number by a divisor that is checked and determined true by a for loop (not the first one, that just loops the program for a determined amount of input.
I'm not sure if there's some way to take the multiple results of the loop and add them together, but that is what I need to do. right now I'm displaying the results of the loop but that was for debugging, in the end the output will be whether it is abundant (the added divisors are over the number), perfect (the added divisors equal the number) or deficient (the added divisors are less then the number)
This is the code in eclipse:
import java.util.*;
public class PerfectNumber {
/**
* #param args
*/
public static void main(String[] args) {
for(int i = 0; i < 15; i++)
{
Scanner reader = new Scanner(System.in);
int number = 0;
int divisor = 1;
int addnum = 0;
System.out.println("Please input a number to check if it is perfect, abundant, or deficient");
number = reader.nextInt();
for(divisor = 1; divisor < number; divisor++)
{
isDivisor(number, divisor);
if(isDivisor(number, divisor) == true)
{
System.out.println(divisor);
}
}
}
}
static boolean isDivisor(int number, int divisor)
{
if (number % divisor == 0)
return true;
else
return false;
}
}
To answer what seems to be your immediate question for what smells like a homework problem ;)
I'm not sure if there's some way to take the multiple results of the loop and add them together
You can check the return of your function as you're already doing and increment a counter
public boolean isSeven(int x){
return x == 7;
}
public static void main(String[] args){
int sumOfSevens= 0;
int i = 0;
while(i < 10){
if(isSeven(7)){
sumOfSevens = sumOfSevens + 7; // or +=
++i;
}
}
// At this point sumOfSevens = 70;
}
You don't need isDivisor because it is equal to the following expression:
number % divisor == 0
Just sum up divisors:
int numDivSum = 0;
for(divisor = 1; divisor < Math.sqrt(number); divisor++)
{
if(number % divisor == 0)
{
numDivSum += divisor;
}
}
and check is the numDivSum is perfect, abundant, or deficient.
If you want to sum things in a loop you can use some statement like this:
Int sum;
// your for loop start
If ( isDivisor(number, divisor))
sum += divisor;
// end of loop
//here you can do the comparison.
There is no need to compare to true in your if-statement. Also this codesnippet only works, if you have only one statement in the if body. If you need to do multiple things, you have to wrap that whole thing in brackets.
Also your first call to isDivisor is useless, as you are not doing anything with the value you get.

Any easier way of finding prime numbers than this?

is there a more efficient, cleaner/elegant way of finding prime numbers than this? The code works fine, but I just wrote what seemed most logical to me and I can't figure out any other way, but to be honest it just doesn't look nice :P. I know coding isn't the most elegant of activities.
Here's my main method:
import java.util.Scanner;
public class DisplayPrimeNumbers
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer that you'd like the system to print the prime numbers till: ");
String input1 = scan.nextLine();
int input = Integer.parseInt(input1);
PrimeGenerator prime = new PrimeGenerator(input);
for (int i = 1; i < input ; i++)
{
if(prime.isPrime())
{
System.out.println(prime.getNextPrime());
}
}
System.out.println(1);
}
}
Here's my class:
public class PrimeGenerator
{
private int number;
public PrimeGenerator(int n)
{
number = n;
}
public int getNextPrime ()
{
return number+1;
}
public boolean isPrime()
{
for(int i = 2; i < number; i++)
{
if (number % i == 0)
{
number--;
return false;
}
}
number--;
return true;
}
}
While this question has already been answered I figured I'd provide my answer anyway in the hopes that somebody may find it useful:
You seem to be primarily concerned with 2 both elegance and efficiency. I'd also like to point out that correctness is equally important. Unless you have a special requirement to treat the number 1 as prime it is no longer considered so. You should equally consider the scenario when the user enters a prime number. You should also give some thought into the boundry condition of what numbers you print. Specifically if I enter the number 7, will your users expect it to output 5,3,2,1 or 7,5,3,2,1. While my personal tendency would be towards the latter, using clear and concise messages can make either option work.
Elegance
The perceived lack of elegance in your solution is largely due to your combination of two concepts: Prime Number Testing and Prime Number Generation.
A Prime Number Test is a (quick) method to determine whether or not a single arbitrarily chosen number is prime.
A Prime Number Generator is a way of generating a sequence of prime numbers which are often consecutive.
As your program demonstrates you can generate a consecutive sequence of prime numbers by testing each number within a given range and only selecting those which are prime! Keeping this as our basic strategy for the moment, let's figure out what the code might:
From our description earlier we said that a prime number test was a method (aka function) to determine if some arbitrarily chosen number was prime. So this method should take as input a(n arbitrarily chosen) number and return wether or not the given numbe was prime (ie: true/false). Let's see how it looks:
public interface PrimeNumberTest
{
bool isPrime(int value);
}
And incorporating your prime number test
public class BruteForcePrimeNumberTester : PrimeNumberTest
{
public bool isPrime(int value)
{
bool isPrime = true;
for(int i = 2; isPrime && i < value; i++)
{
if (value % i == 0)
{
isPrime = false;
}
}
return isPrime;
}
}
Your main program is then responsible for iterating over each number and printing only thsoe which the prime number test identifies as prime.
public static void main(String[] args)
{
//Determine the range of prime numbers to print
Scanner scan = new Scanner(System.in);
System.out.print("Primes smaller than what number should be printed?: ");
int max = Integer.parseInt(scan.nextLine());
//Identify how prime numbers will be tested
PrimeNumberTest test = new BruteForcePrimeNumberTest();
//Uncomment the line below if you want to include the number 1. Favour adding it here so that you may
//use re-use your prime number test elsewhere that atually needs to know if a number is prime.
//System.out.println(1);
//Print the prime numbers
for (int i = 2; i < max ; i++)
{
if(test.isPrime(i))
{
System.out.println(i);
}
}
}
Your main program however should only be concerned with prime number generation. It doesn't really care about the semantics of how those primes are generated we just want the primes. It doesn't really matter if the primes were found via primality testing or any other algorithm. So we ask ourselves what does a prime number generator look like?
For starter primes are always whole numbers so we shouldn't be storing them inside floats, doubles or decimals. That leaves 32 and 64 bit integers. If you want to generate larger prime numbers then obviously you should use the long type but I'm just going to use int. In other languages we would also have to consider things like unsigned numbers too.
Now we need to find a way to return all of these numbers at once. Trees don't really make sense as we're going to be generating a consecutive sequence. Stacks don't make sense because consumers typically want the numbers in the order they were generated. Queues could be used as they fit the first-in-first-out rule. In fact if the end application had an asynchronous prime number generator (producer) and a separate asynchronous consumer this type would be ideal. For this example however I want something read-only. Essentially a prime number generator is an Iterable<int>.
public class PrimeNumberTestGenerator : Iterable<int>
{
private int limit;
private PrimalityTester tester;
public PrimeNumberTestGenerator(PrimalityTester tester, int limit)
{
this.tester = tester;
this.limit = limit;
}
private class PrimeNumberIterator : Iterator<int>
{
private int current;
public PrimeNumberIterator()
{
}
public bool hasNext()
{
return next < limit;
}
public int moveNext()
{
if (!hasNext())
{
throw new NoSuchElementException();
}
int result = next;
do
{
next++;
} while(hasNext() && !tester.isPrime(next));
return result;
}
public void remove()
{
throw new UnsupportedOperationExecution();
}
}
public Iterator<int> iterator()
{
return new PrimeNumberIterator();
}
}
So how do we tie them together?
public static void main(String[] args)
{
//Determine the range of prime numbers to print
Scanner scan = new Scanner(System.in);
System.out.print("Primes smaller than what number should be printed?: ");
int max = Integer.parseInt(scan.nextLine());
//Identify how prime numbers will be tested
Iterable<int> primes = new PrimeNumberTestGenerator(max, new BruteForcePrimeNumberTest());
//Print the prime numbers
foreach (int prime : primes)
{
System.out.println(prime);
}
}
Efficiency
Now the other side of your question was an efficient way of determining the prime numbers within a specified range. While a quick internet search should yield a number of different "fast" algorithms for determing a set of prime numbers that are much faste than the brute force way. One such approach is the Sieve of Atkin:
public class AtkinSieve : Iterable<int>
{
private BitSet primes;
public AtkinSieve(int limit)
{
primes = new BitSet(limit);
int root = (int)Math.sqrt(limit);
primes.set(2);
primes.set(3);
//this section can be further optimized but is the approach used by most samples
for (int x = 1; x <= root; x++)
{
for (int y = 1; y <= root; y++)
{
int number;
int remainder;
number = (4 * x * x) + (y * y);
remainder = number % 12;
if (number < limit && (remainder == 1 || remainder == 5))
{
primes.flip(number);
}
number = (3 * x * x) + (y * y);
remainder = number % 12;
if (number < limit && remainder == 7)
{
primes.flip(number);
}
if (x < y)
{
number = (3 * x * x) - (y * y);
remainder = number % 12;
if (number < limit && remainder == 11)
{
primes.flip(number);
}
}
}
}
for (int i = 5; i <= root; i++)
{
if (primes.get(i))
{
int square = i * i;
for (int j = square; j < limit; j += square)
{
primes.clear(j);
}
}
}
}
}
public class SetBitIterator : Iterator<int>
{
private BitSet bits;
private int next;
private bool isReadOnly;
public SetBitIterator(BitSet bits)
{
this.bits = bits;
next = bits.nextSetBit(0);
}
public bool hasNext()
{
return next <> -1;
}
public int moveNext()
{
int result = next;
next = bits.nextSetBit(next);
return result;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
Conveniently we can now use this prime number generator by only changing a single line in our previous main program!
Change:
//Identify how prime numbers will be tested
Iterable<int> primes = new PrimeNumberTestGenerator(max, new BruteForcePrimeNumberTest());
To:
//Identify how prime numbers will be tested
Iterable<int> primes = new AtkinSieve(max);
You can speed up your search for new primes by storing the primes that you have already found in a private collection inside the PrimeGenerator. By trying only them as potential divisors instead of your for(int i = 2; i < number; i++) loop, you will have to do much fewer divisions
You can stop the "find divisors" loop well before you reach the number: specifically, you can stop when your candidate divisor exceeds the square root of the target number. This works, because you try the candidate divisors in ascending order: if there were divisors above the square root, the result of the division would have been below the square root, so you would have already found them.
Your getNextPrime method should call isPrime internally before returning the value to the caller. Otherwise, the call of getNextPrime cannot be said to return the next prime.
First and most important thing is.... U need not to check till
i
for(int i = 2; i < number; i++)
U need to to check only untill i is less than number/2...
for(int i = 2; i < (number/2); i++)
This is how I might have written it for simplicity
public static void main(String... args) {
System.out.print("Enter an integer that you'd like the system to print the prime numbers till: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
if (input >= 2)
System.out.println(2);
OUTER: for (int i = 3; i <= input; i += 2) { // skip every even number
for (int j = 3; j * j <= i; j += 2) // stop when j <= sqrt(i)
if (i % j == 0)
continue OUTER;
System.out.println(i); // 99+% of the time will be spent here. ;)
}
}
Yeah there are. I don´t know if it´s the most efficient, but it is way more efficient then this one. Check the Miller Rabin test.
Even so, if you want to work with your Code, i could tell you, you should do it like this:
public boolean isPrime(int number)
{
// You should know, that every straight number can not be prime,so you can say i+= 2
if (number == 2)
return true;
if (number % 2 == 0)
{
return false;
}
for(int i = 3; i < number; i+=2)
{
if (number % i == 0)
{
number--;
return false;
}
--number;
return true;
}
Why would a PrimeGenerator produce numbers that are not prime? That's not elegant. Remove the isPrime()-method and rewrite the getNextPrime()-method so that it will always return a prime number.
As an improvement you can step by 6 not by 2 and do 2 checks in each step. See what I found here.
Basically, every number can be written as (6k, 6k + 1, 6k+2, 6k+3,
6k+4, or 6k+5). 6k is clearly not prime. Items 6k+2 to 6k+4 can be
written as 2(3k + 1), 3(2k+1), and 2(3k + 2) and therefore aren’t
prime as they’re divisible by 2 or 3.
So my point is the following. If we want to find numbers up to 1000 we can do the following thing.
int [] primes = new int[1000];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
index = 4;
for(int i = 12; i < 1000; i += 6) {
boolean prime1 = true;
boolean prime2 = true;
int j = 1; // No need to divide by 2, the number is odd.
while(j < index && (prime1 || prime2)) {
if (prime1 && ((i - 1) % primes[j] == 0)) {
prime1 = false;
}
if (prime2 && ((i + 1) % primes[j] == 0)) {
prime2 = false;
}
j++;
}
if (prime1) {
primes[index++] = i - 1;
}
if (prime2) {
primes[index++] = i + 1;
}
}
Try this code mate.I wrote this. This is more elegant i think :)
**import java.util.*;
public class PrimeNum{
public static void main(String args[]){
Scanner x=new Scanner(System.in);
System.out.println("Enter the number : ");
long y=x.nextLong();
long i;
for( i=2;i<y;i++){
long z=y%i;
if(z==0){
System.out.println(y+" is not a prime");
System.out.println(y+" Divide by "+i);
i=y;
}
}if(i==y) System.out.println("Number is prime");
if(y==1) System.out.println("Number 1 is not a prime");
}
}**
Based on my observations a basic approach would be to use this:
int prime(int up_limit){
int counter =0;
for(int i=1;i<=up_limit;i++)
{
if(up_limit%i==0)
counter++;
}
if(count==2){
return up_limit;
}

Categories