Why doesn't my program that computes perfect numbers print anything? - java

I got an assignment to create a program which displays the perfect integers between one and 100. Here is the actual assignment:
Create a PerfectIntegers application that displays all perfect integers up to 100. A perfect integer is a number which is equal to the sum of all its factors except itself. For example, 6 is a perfect number because 1 + 2 + 3 = 6. The application should include a boolean method isPerfect().
I tried and came up with this:
import java.util.ArrayList;
public class PerfectIntegers {
public static boolean isPerfect(int a){
ArrayList<Integer> factors = new ArrayList<Integer>();
int sum=0;
boolean is;
for (int i=1; i<=100; i++){
double r=a/i;
if (r%1==0){
factors.add(i);
}
}for (int i=0;i<factors.size();i++){
sum+=factors.get(i);
}if (sum==a){
is=true;
}else{
is=false;
}return is;
}
public static void getInts(){
for (int i=2; i<=100; i++){
boolean is=isPerfect(i);
if (is!=false){
System.out.print(i+" ");
}
}
}
public static void main(String[] args) {
getInts();
}
}
Eclipse did not show any errors but when I try to run it, the program is terminated and I get nothing.
The problem is likely with double r, as it is not dividing properly 100% of the time.

Your factorization code is wrong. You can fix it like this:
for (int i = 1 ; i < a; i++) {
if (a % i == 0) {
factors.add(i);
}
}
One reason your old code did not work is that you misunderstood the workings of the % operator. It computes the remainder of the division of the left-hand side by the right-hand side, so r % 1 == 0 will be true for all numbers, because 1 divides everything; r % 2 == 0 is a way to detect even numbers, and so on.
The other reason is that you went all the way to 100 in search of divisors. This necessarily includes a, which automatically puts the total above the number itself, because 1 is already on the list.
Once you get this working, you could simplify the code by dropping the list of factors. Since the sum of all factors is all that you need, you might as well compute it in the factorization loop, and drop the loop that follows it:
sum = 0;
for (int i = 1 ; i < a; i++) {
if (a % i == 0) {
sum += i;
}
}

dasblinkenlight has already provided the correct answer. Let me just add that since this seems to be a (potentially graded) assignment you might consider refactoring the getInts() method as well.
boolean is=isPerfect(i);
if (is!=false){
System.out.print(i+" ");
}
is actually equal to
if (isPerfect(i)){
System.out.print(i+" ");
}
since isPerfect() already returns a boolean that can be used inside the condition of the if-statement.
It can be argued (even though I strongly disagree in this concrete case) that it might be more readable to first store the return value in a variable like in in the first variation. But even then you should never have to check for
if (is!=false) { //...
but should be using
if (is) { // ...
instead.

Related

Method to print odd numbers between 1 and 100

I have to write a method that returns/prints the odd numbers between 1 and 100, but I have to use another method, which checks whether a given integer is odd or not:
static boolean isOdd(int c) {
boolean d;
d = c % 2 != 0;
return d;
}
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?), but I think what I'm really struggling with is "connecting" both methods. So the numbers actually run through isOdd() which determines whether they are odd.
I've tried these two options so far, but they're not working.
Option 1:
static void func1() {
int number = 1;
while (number < 100 && isOdd(number)) {
System.out.println(number);
number = number + 1;
}
}
Option 2:
static void func1() {
int i;
for (i = 1; i < 100; i++) {
isOdd(i);
}
System.out.println(i);
}
Your attempt #1 is closer to your goal ;)
you are right that you can use while and for (and probably other kinds of processing multiple numbers, but that just for the sake of completeness, forget it for now)
your println (or print) should be within the loop because you want to print more than just one number.
in you current attempt #1 you end your loop with the first odd number: 1 This doesn't count up very far ;)
So you have to use an if inside your loop where you check the result of isOdd(number) and only print if it's odd.
But the loop has only the upper bound limit as condition (number < 100) as you want to check all the numbers.
Smartass hint (try it only after your program works fine): if you count up by 2 instead by 1 (number = number + 2;), your program will only need half the time - and you could even skip the isOdd check ;-)
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?)
Yes. for-loops are just syntactic sugar for special while-loops:
for (init_stmt; cond; incr_stmt) body_stmt;
is equivalent to
init_stmt;
while (cond) {
body_stmt;
incr_stmt;
}
Let's first write this using a for-loop.
for-loop
for (int i = 1; i < 100; i++)
if (isOdd(i))
System.out.println(i)
Note that we can (and should!) do the declaration of i as int in the for-loop initializer.
Now, we may translate this to an equivalent while-loop:
while-loop
int i = 1;
while (i < 100) {
if (isOdd(i))
System.out.println(i);
i++;
}
Mistakes in your attempts
Attempt 1
You've mistakenly included the check in the condition (rather than using it in an if inside the loop body); the first even number (2) will cause the loop to terminate.
Attempt 2
You're not even using the return value of isOdd here. You're unconditionally printing i after the loop has terminated, which will always be 100.
The ideal implementation
Ideally, you'd not be filtering the numbers; you'd directly be incrementing by 2 to get to the next number. The following loop does the job:
for (int i = 1; i < 100; i += 2)
System.out.println(i);

Getting Time limit exceeded error in java

class Check {
static void countOddEven(int a[], int n) {
int countEven = 0, countOdd = 0;
for (int item : a) {
if (item % 2 == 0) {
countEven++;
}
}
countOdd = n - countEven;
System.out.println(countOdd + " " + countEven);
}
}
Code is to calculate even and odd numbers in an array. Please help to optimise the code.
You’re code is not correct.
If you were meant to count the even and odd numbers in a, then you are counting the even numbers correctly. If n is not equal to the length of a, then your calculation of the count of odd numbers is incorrect.
If on the other hand — and I’m just guessing — you were meant to count the even and odd numbers among the first n elements, then you are counting the even numbers incorrectly since you are iterating over all of a. Also in this case, if n is much smaller than the length of a, there is an optimization in only iterating over the first n elements as you should.
Finally you may try the following version. I doubt that it buys you anything, but I am leaving the measurements to you.
int countOdd = 0;
for (int ix = 0; ix < n; ix++) {
countOdd += a[ix] & 1;
}
int countEven = n - countOdd;
The trick is: a[ix] & 1 gives you the last bit of a[ix]. This is 1 for odd numbers and 0 for even numbers (positive or negative). So we are really adding a 1 for each odd number.
You should try running code with for loop instead of for each loop
Because ,
When accessing arrays, at least with primitive data for loop is dramatically faster.
however
When accessing collections, a foreach is significantly faster than the basic for loop’s array access.
but if you are getting some another errors , so might have done something wrong while calling the method (make sure n=length of your array)
here is the whole code with main method.
class Check{
static void countOddEven(int a[], int n){
int countEven=0,countOdd=0;
for(int i=0;i<n;i++)
if(a[i]%2==0)
{
countEven++;
}
countOdd=n-countEven;
System.out.println(countOdd+" "+countEven);
}
public static void main(String[] arg){
int a[]={2,3,4,5,6};
int n = 5;
countOddEven(a,n);
}
}

two loops in a function?

Is it possible to have two loops in a function?
public static void reduce(Rational fraction){
int divisorNum = 0;
int n = 2;
while(n < fraction.num){
if(fraction.num % n == 0){
divisorNum = n;
System.out.println("n: " + divisorNum);
n++;
}
}
int divisorDenom = 1;
int m = 2;
while(m<fraction.denom){
if(fraction.denom % m == 0){
divisorDenom = m;
System.out.println("m: " + divisorDenom);
m++;
}
}
}
I'm trying to get the greatest common denominator. I know this is the very long way about doing this problem but I just wanted to try having two loops. When I call this function, only the first loop gets printed and not the second. I originally had an if statement, but seeing that the second loop doesn't execute I figured that I fix this part first.
Here's my other part of the code:
public static void main(String[] args){
Rational fraction = new Rational();
fraction.num = 36;
fraction.denom = 20;
reduce(fraction);
}
Absolutely. There are no limitations
Watch your conditional test = is not quite ==
Based on your edit I suspect fraction.denom is initialized at 1 or 0
Hence you will never get in the second loop
You can have any number of loops in your function :-
1.You can have nested loops;
2.Two loops side by side.
SO,your piece of code is fine enough considering the value of n, until the conditions for loop execution are met :-
public static void ....
while(n<x){
do this
add to counter
}
while(m<x){
do this
add to counter
}
if(y==z){ // NOTE :- Here you have committed mistake, compare using ==, not by =(it will be always true else and your condition will always be met else)
print this
}
Yup. You even can have 3 if you try hard enough.
EDIT: The didactic version:
Loops, as the name suggest, are constructs that allow you to repeat blocks of code several times (post conditional loops -> until certain condition is met keep running, pre conditional loops -> if certain condition is met, keep running). This is often called "iteration". So in a typical for-loop:
for ( int i = 0; i < 10; ++i )
print(array[i]);
You can say you're "iterating" over the array 10 times.
This has nothing to do with functions. You can have several loops inside a function, or functions being called inside loops. As long as you define your "blocks" of code (with begining and ending braces) you do what you think its best.
Yes, there are no limitations when it comes to looping. You could do 1000 while loops if you wanted.
An example here could be doing something like making a square out of *...
Here's an example
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
System.out.print("*");
}
System.out.println();
}
It would look like:
****
****
****
****

modulo algorithm for prime numbers

I'm trying to get a program to get me the prime numbers from a certain range (user inputs the maximum number) and this variable called maxNumber will be used to stop the while loop. The control variable used starts at the first prime number 2 and is called i and will be used to print out the prime numbers (when found) and natural numbers, respectively.
My problem is that I'm not really sure if my algorithm inside the main method and mutator method are both correct and I have a problem where I am putting the user input (the max number) but nothing is happening at all after that -- basically, it is compiling and running but not responding when inputting the first variable.
Help would very much be appreciated !
import java.util.*;
public class PrimeCalculator {
private static int maxNumber;
private static int divisibleCount;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int i = 2;
System.out.println("Enter the maximum amount of numbers you want to find prime numbers within: ");
maxNumber = scanner.nextInt();
while(i <= maxNumber)
isPrime(i);
if(divisibleCount < 2)
System.out.println(i + " is a prime number");
if(divisibleCount > 2)
System.out.println(i + " is not a prime number.");
divisibleCount = 0;
i++;
}
public static void isPrime(int n) {
divisibleCount = 0;
for(int x = 1; x <= maxNumber; x++ )
if(n%x == 0)
divisibleCount++;
}
}
Although I do not think it is clear what you're asking, I will make a few suggestions.
First of all, at your main method, change if(divisibleCount < 2) to if(divisibleCount <= 2) because primes are divided by 1 and themselves (so, "divisibleCount" is 2).
Also, in your while loop, you should check if i equals one and say that it is not a prime.
As said in the comments, at the isPrime method , you can change the loop to for(int x = 1; x <=n; x++ ) as it is impossible for a number to be perfectly divided by soomething greater (i.e. 6 divided by 10 cannot have modulo 0)
EDIT: As dcsohl suggested, it is even better to have for(int x = 1; x <= Math.sqrt(n); x++) (see comment)
Check your syntax. At the while loop, you do not open and close brackets, so only isPrime(i) gets executed in the loop. Imagine
while(i <= maxNumber){
isPrime(i);
}
if(divisibleCount < 2) // ....etc
And since i is never incremented in the loop, it it always 2, so ... we have got an infinite loop!
(General improvement) Surround the maxNumber = scanner.nextInt(); in a try-catch block to avoid crashing when entering say, a string instead of an int.
These are the problems I found, hope I helped you.
PS. If you have any other question like this (i.e. general code checking), you should ask them at Code Review rather than Stack Overflow
I won't answer your Java questions, but the normal algorithm for enumerating the prime numbers is the Sieve of Eratosthenes, invented by a Greek mathematician over two thousand years ago:
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n
if sieve[p]
output p # prime
for i from p*p to n step p
sieve[i] := False
This algorithm examines every number p from 2 to n; if p is prime, the loop on i marks False all the multiples of p; the i loop starts from the square of p because all smaller multiples will already have been marked False by smaller primes.
If you're interested in programming with prime numbers, I modestly recommend this essay at my blog.
import java.io.*;
class Prime
{
public static void main(String args[])
{
long i,j,n=1000000100000L;
long sum=0;
long i1=1000000000000L;
long c;
System.out.println("The Prime Numbers are:");
for(i=i1;i<=n;i++)
{
c=0;
for(j=2;j<=10000000;j++)
{
if(i%j==0)
c=c+1;
if(c==1)
break;
}
if(c==0)
{
System.out.println(i);
sum=sum+i;
}
}
System.out.println("The Sum of Prime numbers are:"+sum);
}
}

Are for loops and while loops always interchangeable

I understand the concept of one having certain advantages over the other depending on the situation but are they interchangeable in every circumstance? My textbooks writes
for (init; test; step) {
statements;
}
is identical to
init;
while (test) {
statements;
step;
}
How would I rewrite the following program in the for loop? I'm having trouble setting the value for the init and the test if i rework the following program into the for loop form.
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("this program sums the digits in an integer");
int n = readInt("enter a positive number: ");
int dsum = 0;
while ( n > 0) {
dsum += n % 10;
n /=10;
}
}
}
int dsum = 0;
for(int n = readInt("enter a positive number: "); n > 0; n /=10) {
dsum += n % 10;
}
As I can't stop myself from writing this, so I'll point it out.
Your for loop: -
for (init; test; step) {
statements;
}
Is not identical to the while loop you posted. The init of the for loop will not be visible outside the loop, whereas, in your while loop, it would be. So, it's just about scope of the variable declared in init part of for loop. It is just inside the loop.
So, here's the exact conversion of your for loop: -
{
init;
while (test) {
statements;
step;
}
}
As far as the conversion of your specific case is concerned, I think you already got the answer.
Well, by the above explanation, the exact conversion of your while loop is a little different from the #Eric's version above, and would be like this: -
int dsum = 0;
int n = 0;
for(n = readInt("enter a positive number: "); n > 0; n /=10) {
dsum += n % 10;
}
Note that this has a very little modification from the the #Eric's answer, in that, it has the declaration of loop variable n outside the for loop. This just follows from the explanation I gave.
Beside the scope of variables declared in the initializer, there is another time when a for will exhibit different behavior, which is in the presence of a continue:
for (init; test; update) {
if(sometest) { continue; }
statements;
}
is NOT identical to
init;
while (test) {
if(sometest) { continue; }
statements;
update;
}
because in the while loop the continue it will skip update, where the for loop will not.
To show this via the starkest of examples, consider the following two loops (thanks #Cruncher):
// terminates
for(int xa=0; xa<10; xa++) { continue; }
// loops forever
int xa=0;
while(xa<10) { continue; xa++; }
+1, good question
The difference between the two is mostly eye-candy. In the one instance the one may simply read better than the other. For your example, the following is the for-loop equivalent in a single line of code. In this case, however, the while loop reads easier.
public void run() {
println("this program sums the digits in an integer");
for (n = readInt("enter a positive number: "), dsum=0; n > 0; dsum+=n%10, n/=10);
}
Yes, except for the two things:
"For" let you declare and initialize your conditions (= variables, btw - more than one variable!) in it, and then it is cleaned up automatically, as you leave the "For" cycle.
Whereas with "While" you will have to do it yourself, initialize - outside the "While", clean up - only as you leave the of visibility where your variables (for conditions) were declared.
"For" has convenient syntax (and all cleanup afterwards) for iteration over collections and arrays.
Your code I would rewrite this way:
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("this program sums the digits in an integer");
for(int n = readInt("enter a positive number: "), dsum = 0; n > 0; n /=10) {
dsum += n % 10;
}
}
}
Don't forget - in init you can place declaration/initialization for more than one variable.
what kind of difficulties you have,anyway
int n = readInt("enter a positive number: ");
for(n;n>0;n=n/10)
{dsum+=n%10;
}
This should work. Replace your while loop with this. Just leave the initialization part empty.
for(;n>0;n=n/10)
{
dsum+=n%10;
}

Categories

Resources