I'm trying to create a perfect number test for a range of numbers, with n being the start number and endNum being the end number. It won't loop properly, but the perfect number test (portion inside the "while" loop) works by itself. What am I doing wrong?
import java.util.Arrays;
import java.util.Scanner;
public class CodingChallenge3 {
public static void main(String[] args) {
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Welcome to the Perfect Number Tester."
+ "\n" + "Enter a number range."
+ "\n" + "From: ");
n = s.nextInt();
System.out.print("To: ");
int endNum = s.nextInt();
while (n <= endNum) {
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum = sum + i;
}
}
if (sum == n && n != 0) {
System.out.println(n + " is perfect");
}
if (sum > n) {
System.out.println(n + " is imperfect abundant");
}
if (sum < n) {
System.out.println(n + " is imperfect deficient");
}
if (n == 0) {
System.out.println(n + " has no factors");
}
n++;
}
}
}
You forgot to reset the sum for each value of n:
while (n <= endNum) {
sum = 0; // add this
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum = sum + i;
}
}
if (sum == n && n != 0) {
System.out.println(n + " is perfect");
}
if (sum > n) {
System.out.println(n + " is imperfect abundant");
}
if (sum < n) {
System.out.println(n + " is imperfect deficient");
}
if (n == 0) {
System.out.println(n + " has no factors");
}
n++;
}
Related
I'm not that new with Java (studied it years ago but stopped for 5-6 years because of work) and I'm trying to get in touch with it again. A friend of mine gave me practice problems I could work with to practice, but it is quite hard for me. It is basically showing the steps in finding GCD using Euclidean Algorithm. I did everything, but the last detail needed for the GCD is missing once I input a big number.
Here is the code I've done so far:
import java.util.Scanner;
class mpONE {
public static void main (String[] args)
{
System.out.println("Finding GCD Using Euclid's Algorithm");
Scanner num = new Scanner(System.in);
System.out.println("Enter your first (higher) number: ");
int n1 = num.nextInt();
System.out.println("Enter your second (lower) number: ");
int n2 = num.nextInt();
System.out.println("Numbers for finding GCD are: " + n1 + " " + n2);
System.out.println("Computing for GCD... ");
for (int i = 0; i <= n2; i++)
{
int g = n1/n2;
int f = (g * n2);
int h = n1 - f;
System.out.print(n1 + " = " + "(" + n2 + " * " + g + ") + " + h);
n1 = n2;
n2 = h;
System.out.println();
if (h == 0)
{
break;
}
}
for (int i = 1; i <= n1 && i <= n2; ++i) {
if (n1 % i == 0 && n2 % i == 0)
{
int ans = i;
System.out.println("Your GCD is " + ans);
}
}
}
}
With smaller numbers, it does work (the "+ h" should be 0), but with big numbers, it stops just before it shows the 0 remainder. Thanks for your help!
Just change the location of the if(h==0) block:
import java.util.Scanner;
class mpONE {
public static void main (String[] args)
{
System.out.println("Finding GCD Using Euclid's Algorithm");
Scanner num = new Scanner(System.in);
System.out.println("Enter your first (higher) number: ");
int n1 = num.nextInt();
System.out.println("Enter your second (lower) number: ");
int n2 = num.nextInt();
System.out.println("Numbers for finding GCD are: " + n1 + " " + n2);
System.out.println("Computing for GCD... ");
for (int i = 0; i <= n2; i++)
{
int g = n1/n2;
int f = (g * n2);
int h = n1 - f;
System.out.print(n1 + " = " + "(" + n2 + " * " + g + ") + " + h);
System.out.println();
if (h == 0)
{
break;
}
n1 = n2;
n2 = h;
}
for (int i = 1; i <= n1 && i <= n2; ++i) {
if (n1 % i == 0 && n2 % i == 0)
{
int ans = i;
System.out.println("Your GCD is " + ans);
}
}
}
}
I am currently attempting to solve a ProjectEuler problem and I have got everything down, except the speed. I am almost certain the reason the program executes so slowly is due to the nested loops. I would love some advice on how to speed this up. I am a novice programmer, so I am not familiar with a lot of the more advanced methods/topics.
public class Problem12 {
public static void main(String[] args) {
int num;
for (int i = 1; i < 15000; i++) {
num = i * (i + 1) / 2;
int counter = 0;
for (int x = 1; x <= num; x++) {
if (num % x == 0) {
counter++;
}
}
System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
}
}
}
EDIT : Below is the new code that is exponentially faster. Removed the constant line printing as well to speed it up even more.
public class Problem12 {
public static void main(String[] args) {
int num;
outerloop:
for (int i = 1; i < 25000; i++) {
num = i * (i + 1) / 2;
int counter = 0;
double root = Math.sqrt(num);
for (int x = 1; x < root; x++) {
if (num % x == 0) {
counter += 2;
if (counter >= 500) {
System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
break outerloop;
}
}
}
}
}
}
For starters, when looking at divisors, you never need to go further than the root square of the number, because each divisor below the square root has an equivalent above.
n = a * b => a <= sqrt(n) or b <= sqrt(n)
Then you need to count the other side of the division:
double root = Math.sqrt(num);
for (int x = 1; x < root; x++) {
if (num % x == 0) {
counter += 2;
}
}
The square root is special because it counts only once if it is integer:
if ((double) ((int) root) == root) {
counter += 1;
}
You just need to factorize the number. p^a * q^b * r^c has (a+1)*(b+1)*(c+1) divisors. Here is some basic implementation using this idea:
static int Divisors(int num) {
if (num == 1) {
return 1;
}
int root = (int) Math.sqrt(num);
for (int x = 2; x <= root; x++) {
if (num % x == 0) {
int c = 0;
do {
++c;
num /= x;
} while (num % x == 0);
return (c + 1) * Divisors(num);
}
}
return 2;
}
public static void test500() {
int i = 1, num = 1;
while (Divisors(num) <= 500) {
num += ++i;
}
System.out.println("\nFound: [" + i + "] - " + num);
}
I have been working on this program for a few hours and the code is working correctly but I can't seem to get it to print out correctly, it should just be printing once for each value, such as:
number: 6
dividers: 2 3 6 1
prime: is not prime
Output
Can anyone help? Screenshot is attached. Thanks!
public static void main(String[] args) {
Random randomNums = new Random();
int count;
for (int i = 1; i <= 37; i++) {
count = randomNums.nextInt(100) + 1;
System.out.println("number " + count);
for (int b = 1; b<=count; b++) {
if (count % b == 0) {
System.out.println("dividers " + b);
}
}
for (int a = 2; a< count; a++) {
if (count % a == 0) {
System.out.println("is not prime");
}
if (count % a != 0) {
System.out.println("is prime");
}
}
}
}
}
try to write this code :
public static void main(String[] args) {
Random randomNums = new Random();
int count;
for (int i = 1; i <= 37; i++) {
count = randomNums.nextInt(100) + 1;
System.out.println("number " + count);
String dividers = "";
for (int b = 1; b<=count; b++) {
if (count % b == 0) {
dividers += b.toString() +" ";
}
}
// control the print beside loop
System.out.println("dividers " + dividers);
// add the control for whether prime
bool prime = true;
for (int a = 2; a< count; a++) {
if (count % a == 0) {
System.out.println("prime : is not prime");
// add the control for skip loop
prime = false;
break;
}
}
if(prime){
System.out.println("prime : is prime");
}
}
}
}
based upon your logic, I am guessing that if you decide that a number is not a prime then that is the final result,
so
boolean isPrime = true;
String dividers = "";
for (int a = 2; a< count; a++) {
if (count % a == 0) {
isPrime = false;
dividers += a+" ";
}
}
if (isPrime) {
System.out.println ("is Prime");
} else {
System.out.println ("dividers "+dividers);
System.out.println ("is not Prime");
}
Made some edits to the code to try and figure out why my X's [-1] are not being included in finding my average for that row. That is throwing of my averages. Any idea why It is not counting my -1's?
output[expected]:
USER INPUT: 3
O O O
X X X
X X X
TOTAL OPENNESS OF [I][J] = 1
TOTAL OPENNESS OF [I][J+1] = 2
TOTAL OPENNESS OF [I][J+2] = 1
TOTAL SUM AVERAGE FOR THAT ROW = 1.3
HOWEVER..FOR ROW 2 AND ROW 3
TOTAL SUM AVERAGE FOR THOSE ROWS = 0
WHICH IS INCORRECT IT SHOULD = -1
public static void openfactor(char[][] mazeValue, int n){
for(int i = 1; i<=n; i++)
{
double rowAvg=0;
double totalRowAvg=0;
for(int j=1;j<=n;j++)
{
int count=0;
int totalOpeness=0;
int totalRowOpeness = 0;
//double rowAvg=0;
if(mazeValue[i][j]=='X'){
System.out.println("tHIS IS AN X FOR : [" + i + "]" +"[" + j + "] IS -1 ");
count = -1;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=1)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1 && j-1>=1)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n && i+1<=n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<=n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=1 && i+1<=n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=1 && j+1<=n)
{
if(mazeValue[i-1][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " +totalOpeness);
totalRowOpeness = totalRowOpeness + totalOpeness;
//}//eND OF iF CONDITION\
}
rowAvg = (double)totalRowOpeness/(double)n;
System.out.println("ROW AVERAGE: "+rowAvg);
totalRowAvg = totalRowAvg + rowAvg;
System.out.println("SUM ROW AVERAGE: "+totalRowAvg);
}
System.out.println("TOTAL SUM ROW AVERAGE: " +totalRowAvg);
}
}
public static void printMaze(char mazeValue[][]) {
System.out.println("MAZE");
for (int i = 1; i < mazeValue.length; i++) {
for (int j = 1; j < mazeValue[i].length; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n + 1][n + 1];
System.out.println("ENTER A PATH: ");
for (int i = 0; i < mazeValue.length; i++) {
for (int j = 0; j < mazeValue[i].length; j++) {
if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
mazeValue[i][j] = 'X';
else {
mazeValue[i][j] = kbd.next().charAt(0);
}
}
}
printMaze(mazeValue);
horizontalPath(mazeValue, n);
System.out.println(" ");
verticalPath(mazeValue,n);
System.out.println(" ");
openfactor(mazeValue, n);
}
}
I do not completely understand what u want to accomplished but I am going to to assume you want to find repeated values, do this using some search algorithm below is an example of a binary search. Hope it helps.
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
Here's the complete code for your request. you need to reorder your if statements a little bit your logic was right:
and here is the output :
MAZE
O O X
O O O
X X O
TOTAL OPENESS FOR : [0][0] IS 3
TOTAL OPENESS FOR : [0][1] IS 4
THERE IS AN X HERE FOR : [0][2]
Average of O's in this row is : 66.66667%
TOTAL OPENESS FOR : [1][0] IS 3
TOTAL OPENESS FOR : [1][1] IS 5
TOTAL OPENESS FOR : [1][2] IS 3
Average of O's in this row is : 100.0%
THERE IS AN X HERE FOR : [2][0]
THERE IS AN X HERE FOR : [2][1]
TOTAL OPENESS FOR : [2][2] IS 2
Average of O's in this row is : 33.333336%
here's the code:
import java.util.Scanner;
public class sof {
public static boolean IsOutOfBound(int i, int j, int n)
{
if (i-1<1 || j-1<1 || i+1>n || j+1>n)
return true;
else
return false;
}
public static void openfactor(char[][] mazeValue, int n)
{
for(int i = 0; i<n; i++)
{
int TotalCounts=0;
for(int j=0;j<n;j++)
{
int count=0;
if(mazeValue[i][j]=='X'){
System.out.println("THERE IS AN X HERE FOR : [" + i + "]" +"[" + j + "] ");
//TotalCounts--;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=0)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0 && j-1>=0)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n && i+1<n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=0 && i+1<n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=0 && j+1<n)
{
if(mazeValue[j+1][i-1]=='O')
count++;
}
// System.out.println("cout: "+count);
//totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " + count);
TotalCounts++;
}//END OF else CONDITION
}//End of J loop
float Average = ((float)TotalCounts/(float)n) * 100;
System.out.println("Average of O's in this row is : " + Average+ "%");
}//End of I loop
}
public static void printMaze(char mazeValue[][],int n) {
System.out.println("MAZE");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for (int i = 0; i <n; i++) {
for (int j = 0; j < n; j++) {
//if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
// mazeValue[i][j] = 'X';
// else {
mazeValue[i][j] = kbd.next().charAt(0);
// }
}
}
printMaze(mazeValue,n);
openfactor(mazeValue, n);
}
}
public static void notDivisible(int n, int x, int y)
{
Scanner kb = new Scanner(System.in);
System.out.println("These are the ints from 1 to" + n + "that are not divisible by" + x + "or" + y);
n = kb.nextInt();
x = kb.nextInt();
y = kb.nextInt();
if((n%x) == 0)
{
}
else
{
System.out.println()
}
if((n%y) == 0)
{
}
else
{
System.out.println();
}
So this is all I have so far. I know that I have to use modulus and print out the numbers that aren't divisible by the number, but how can I do it?
Reading "not divisible by x or y" as "divisible by neither x nor y":
for (int i = 1; i <= n; ++i) {
if (i%x!=0 && i%y!=0) {
System.out.println(i);
}
}
Make a loop from 1 to the limit (n).
for(int i = 1; i < n; i++)
{
if(i % x != 0 || i % y != 0)
{
System.out.println(i);
}
}
The modulus (%) is the rest of the division. If i % x is different from 0 that means i cannot be divided by x.
First of all you will need to ask the user the numbers n, x and y before printing them.
Then what you want to achieve is a typical job for for loops:
for(int i=0; i<n; ++i) {
if(i%x != 0 && i%y != 0) {
System.out.println(i);
}
}
Try doing your next exercise alone ;)
This reeks of homework. But against my better judgment:
for(int z=1; z<n; z++) { // Test all numbers from 1 to n
if((z % x) == 0) {
System.out.println(z + " is divisible by " + x);
} else System.out.println(z + " isn't divisible by " + x);
if((z % y) == 0) {
System.out.println(z + " is divisible by " + y);
} else System.out.println(z + " isn't divisible by " + y);
}