Following is my code which adds products of all 3 digit numbers into an array List. Then prints those numbers which are palindrome. I am getting 121 as output. Why not other palindrome number??
import java.util.ArrayList;
public class eular {
int reverse=0;
public boolean palindrome( Integer num){
int remainder=0;
int n=num;
while(num!=0){
remainder = num % 10;
reverse = reverse * 10 + remainder;
num = num / 10;
}
if(n==reverse)
return true;
else
{
return false;
}
}
public static void main(String args[]){
eular e=new eular();
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=100;i<=999;i++)
for(int j=100;j<=999;j++){
a.add(i*j);
}
for (Integer integer : a) {
if(e.palindrome(integer)){
System.out.println(integer);;
}
}
}
}
Your reverse variable should be initialized every time you call a palindrome method. Move the line int reverse=0; inside that method.
First, you've forgot to declare reverse (edit: or did it in the wrong context as a field of euler class: in that case you have to assign reverse to zero before each call of the palindrome):
// static: you don't want "this"
public static boolean palindrome(Integer num) {
int n = num;
int reverse = 0; // <- this was omitted (or misplaced as a field of euler)
while (num != 0) {
reverse = reverse * 10 + num % 10;
num = num / 10;
}
// ifs can be so ugly...
return n == reverse;
}
Second, you don't want that huge arrays:
...
for (int i = 100; i <= 999; i++)
for (int j = 100; j <= 999; j++) {
int item = i * j;
if (palindrome(item))
System.out.println(item);
}
Related
So I am very new to learning java and I have a sub class which contains the main and a parent class which does all the calculations. I am having problems on how to pass the elements of an array from the main class to the parent class.
Here is my code. Please help me with how to instantiate the array.
import java.util.Scanner;
public class GreatestLeastAverageApp {
public GreatestLeastAverageApp() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
GreatestLeastAverage number = new GreatestLeastAverage();
int[] x = {0};
int a = 0, b = 0;
x = new int[a];
{
for (int i = 0; i <= a; i++)
{
for (int j = 0; j <= a; j++)
GreatestLeastAverage.a[i] = x[j]; // loop to pass the values of the array elements to the parent class from the sub class.
}
}
Scanner keyboard = new Scanner(System.in); // for the input from the user
System.out.println("Enter the number of elements:");
a = keyboard.nextInt(); // enter the number of integers to be entered so loop can run accordingly
System.out.println("Enter a set of integers( Enter -99 to exit):");
do // do loop so the user can input the variables until one of the variable is =-99.
{
{
for (b = 0; b <= a; b++)
x[b] = keyboard.nextInt();
}
} while (x[b] != -99);
//GreatestLeastAverage number = new GreatestLeastAverage(); // object made for parent class.
System.out.println("The Greatest Number is" + number.computegreatest()); // output line.
System.out.println("The Smallest Number is" + number.computeleast());
System.out.println("The average is " + number.computeaverage());
keyboard.close();
}
}
public class GreatestLeastAverage {
static int x; //variables declared for input in super class.
public static int[] a; // static variable to access in both classes.
int temp;
int temp1;
int temp2;
int average;
public int greatestleastaverage(int d) {
d = x;
return x;
}
public static int getarray(int[] b) {
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= x; j++) {
a[i] = b[j];
}
}
return b[];
}
I know you can't return elements of an array but I really need help.
Use Lists. They're generally more flexible, and if you use ArrayList properly, it can be virtually just as performant as an array.
public class GreatestLeastAverage {
// ... other private members
private List<Integer> a = new ArrayList<Integer>();
public List<Integer> getA() {
return a;
}
}
This lets you do code like:
GreatestLeastAverage gla = new GreatestLeastAverage();
for (int b = 0; b <= a; b++) {
gla.getA().add(keyboard.nextInt());
}
If you should require that data for other uses, it's in gla already! Simply reuse it.
for(int a : gla.getA()) {
// Do something with a
}
I'm sure you used static members because you didn't know how to make it work otherwise, but just know that using static members is generally discouraged unless they're final (constant).
You shouldn't pass data (array) to methods in GreatestLeastAverage class by setting the value of the static field (public static int[] a;). Instead you should pass data to methods as theirs arguments. Your program should look like this:
import java.util.Scanner;
public class GreatestLeastAverageApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int numOfElems = input.nextInt();
int[] numbers = new int[numOfElems];
System.out.println("Enter a set of integers:");
for (int i = 0; i < numOfElems; i++) {
numbers[i] = input.nextInt();
}
System.out.println("Statistics:");
System.out.println(" min: " + GreatestLeastAverage.findMin(numbers));
System.out.println(" max: " + GreatestLeastAverage.findMax(numbers));
System.out.println(" average: " + GreatestLeastAverage.findAverage(numbers));
}
}
class GreatestLeastAverage {
public static int findMin(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num < candidate) candidate = num;
}
return candidate;
}
public static int findMax(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num > candidate) candidate = num;
}
return candidate;
}
public static double findAverage(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum / (double) numbers.length;
}
}
To make this code even better:
The min/max/average calculations above are not great, e.g. If you pass empty array to findAverage, then numbers.length will be 0 and you'll divide by 0. You should make those calculations better, see: #1, #2, #3.
Consider using ArrayList instead of array, when you need to dynamically change the size of the list during runtime (See Neil's answer).
How to use multiple methods in a code? First it asks for the size of an array, then for the numbers of the element. One method is rounding numbers with a special rule.
Second method is a void method which modifies the array. Third method is making a new array with the modified values and returns to this array.
package tombtombbekerekit;
import java.util.Scanner;
public class TombTombbeKerekit {
public static int round(int osszeg)
{
int last_Digit = osszeg % 10;
if(last_Digit < 3)
return osszeg - last_Digit;
else if(last_Digit > 7)
return osszeg + (10 - last_Digit);
else
return osszeg - (last_Digit) + 5;
}
public static void roundSelf(int [] numbers)
{
int[] array = numbers;
for (int i = 0; i < array.length; i++)
return;
}
public static int [] roundNew(int [] numbers)
{
int [] newArray = new int[numbers.length];
return newArray;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Kérem az összegek számát: ");
int size = sc.nextInt();
System.out.println("Kérem az összegeket: ");
int [] array = new int[size];
for (int i = 0; i < array.length; i ++)
{
array[i] = sc.nextInt();
}
int [] kerek = roundNew(array);
System.out.println("Kerekítve: ");
for (int i = 0; i < kerek.length; i++)
System.out.println(kerek[i]);
}
}
You should write your own function. Just find the rule for the rounding. You can use n%10 to get the last digit of an integer named n.
I've written something but haven't tested it, I believe it should work. Check it out:
public int weirdRounding(int n)
{
int last_Digit = n % 10;
if(last_Digit < 3)
return n - last_Digit;
else if(last_Digit > 7)
return n + (10 - last_Digit);
else // the last digit is 3,4,5,6,7
return n - (last_Digit) + 5;
}
Note: You should probably make this code more readable if you're going to use it. For example define int LOWER_BOUND = 3 and int UPPER_BOUND = 7 instead of using '3' and '7', you could also wrap the ugly expressions with functions (e.g. roundUp, roundToFive ..). #Magic_Numbers_Are_Bad
I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1
{
public static void main()
{
int num, sum=0;
int i;
for(num=1; num<100; num++)
{
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
Change your code to :
public static void main(String[] s1) throws Exception {
int num, sum = 0;
int i;
for (num = 1; num < 100; num++) {
for (int j = 1; j <= num - 1; j++) { // change made here
if (num % j == 0) {
sum = sum + j;
}
}
if (sum == num) {
System.out.println(sum);
}
sum = 0; // change made here
}
}
Key takeaways:
Reset sum to 0 once done with inner iteration
In your inner for-loop you need to check if till num - 1 and not num because every number is divisible by itself
1) you definitely need to reset your sum variable for every iteration, so you should do int sum = 0; in every loop.
2) you need to iterate while j <= num/2;!
3) consider using Java 8, I'll write some sample here for you.
See my example here, this is so beautiful:
public class PerfectNumbersDemo {
public static void main(String[] args) {
IntStream.range(1, 100)
.filter(PerfectNumbersDemo::isPerfect)
.forEach(System.out::println);
}
private static boolean isPerfect(int number) {
return number == IntStream.rangeClosed(1, number / 2)
.filter(i -> number % i == 0)
.sum();
}
}
This seems to be an assignment or homework question. You are meant to solve this by yourself and not ask it to the people on Stack overflow.
However, what you are looking for has an answer here. Beware! This code prints if the input number is perfect number or not but does not print all the numbers below 100 that could be perfect numbers. That is your homework.
You need to:
sum = 0 with every loop iteration
iterate until < num and not <= num
Here's the fixed code:
public static void main(String[] args) {
int sum;
for(int num = 1; num < 100; num++) {
sum = 0;
for(int j = 1; j< num; j++) {
if(num % j == 0) {
sum += j;
}
}
if(sum == num) {
System.out.println(sum);
}
}
}
Output:
6
28
So, your code have some minor problems and I will try to pinpoint them out.
1.First of all your sum variable should be inside the first for loop
2. The limit upto which the second loop will run will be j<num not j<=num because, for the perfect number, the number itself shouldn't be counted in the sum.
You code will look like this.
I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1 {
public static void main()
{
int num;
for(num=1; num<100; num++)
{
int sum = 0;
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
public class factors{
public static void main(String args[]){
int sum=0;
for(int k=2;k<=30;k++){
for(int i=1;i<k;i++)
{
if(k%i==0)
sum=sum+i;
}
if(k==sum)
System.out.println(sum);
sum=0; //sum=0 is very important.
}
}
}
OUTPUT
6
28
class PERFECT
{
public static void main(String args[])
{
int i,j,S,
for(i=1;i<=100;i++)
{
S=0
for(j=1;j<i;j++)
{
if(i%j==0)
S+=j;
if (S==i)
System.out.println(i+"is perfect");
}
}
}
}
Here is an alternate way of finding perfect numbers.
if 2p-1 is prime when p is prime. Then (2p-1)(2p-1) is a perfect number. 2p-1 is known as a Mersenne Prime
As these numbers get real big real fast, using BigInteger is recommended.
This computes the first 10 perfect numbers.
int N = 10;
int count = 1;
for(int i = 2; i < 10_000; i += i == 2 ? 1 : 2) {
BigInteger val = BigInteger.valueOf(i);
if (val.isProbablePrime(99)) {
BigInteger mersenne1 = (BigInteger.ONE.shiftLeft(i)).subtract(BigInteger.ONE);
if (!mersenne1.isProbablePrime(99)) {
continue;
}
BigInteger mersenne2 = BigInteger.ONE.shiftLeft(i-1);
System.out.printf("%3d: %,d\n",count, mersenne1.multiply(mersenne2));
if (count++ >= N) {
break;
}
}
}
prints
1: 6
2: 28
3: 496
4: 8,128
5: 33,550,336
6: 8,589,869,056
7: 137,438,691,328
8: 2,305,843,008,139,952,128
9: 2,658,455,991,569,831,744,654,692,615,953,842,176
10: 191,561,942,608,236,107,294,793,378,084,303,638,130,997,321,548,169,216
I need to write a java method sumAll() which takes any number of integers and returns their sum.
sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20
I don't know how to do this.
If your using Java8 you can use the IntStream:
int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());
Results: 181
Just 1 line of code which will sum the array.
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
Use var args
public long sum(int... numbers){
if(numbers == null){ return 0L;}
long result = 0L;
for(int number: numbers){
result += number;
}
return result;
}
import java.util.Scanner;
public class SumAll {
public static void sumAll(int arr[]) {//initialize method return sum
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum is : " + sum);
}
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);//create scanner object
System.out.print("How many # you want to add : ");
num = input.nextInt();//return num from keyboard
int[] arr2 = new int[num];
for (int i = 0; i < arr2.length; i++) {
System.out.print("Enter Num" + (i + 1) + ": ");
arr2[i] = input.nextInt();
}
sumAll(arr2);
}
}
public static void main(String args[])
{
System.out.println(SumofAll(12,13,14,15));//Insert your number here.
{
public static int SumofAll(int...sum)//Call this method in main method.
int total=0;//Declare a variable which will hold the total value.
for(int x:sum)
{
total+=sum;
}
return total;//And return the total variable.
}
}
You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:
int sum = 0;
for (int i = 0; i < arrayLength; i++) {
sum += arrayVal[i];
}
System.out.println("the sum is" + sum);
I hope this helps.
I have an algorithm that uses a List in Java that is declared like this:
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
return factors;
}
What I would like to be able to do is to take the primes returned by this function and add them. I know I can use
for (Integer integer : primeFactors(NUMBER))
to do something with every prime added to the List, so I am guessing the answer will be something along these lines when I add them. Is something like this possible?
Thanks for any and all help.
So basically have a variable outside the loop, and then you can do something like this:
List list = primeFactors(NUMBER);
int sum = 0;
for(Integer number : list){
sum += number;
}
At the end of that loop, sum will contain the number you want!
You can do addition of the elements that you want in your algorithm because you already iterating on the elements. the function will return 18 for primeFactors(65) -> 5*13
public static void main(String[] args) {
int sumOfPrimeFactors = primeFactors(65);
System.out.println(sumOfPrimeFactors);
}
public static int primeFactors(int numbers) {
int sum = 0;
int n = numbers;
int i;
for (i = 2; i <= n / i; i++) {
while (n % i == 0) {
sum += i;
n /= i;
}
}
if (n > 1) {
sum += n;
}
return sum;
}