Find the smallest number M, which is divided by exactly n-1 numbers from the input array. If there is no such M then return -1.
Example:
array = [2,3,5]
Answer :
6
Explanation :
6 can be divided by 2 and 3
Example:
array = [2,3,6]
Answer:
-1
Explanation :
It's not possible in this case so return -1.
My code:
As we need to find the smallest M, I am selecting only the elements from 0 to n-2
public int process(int[] arr) {
int answer = 1;
for(int i=0; i<arr.length-1; i++) {
answer *= arr[i];
}
return answer;
}
This program works for these 2 sample test cases but it was failing for multiple hidden test cases. I trying to understand what I am missing here.
Calculation of the Least Common Multiple (LCM)
A problem inside the task is the calculation of the Least Common Multiple of 2 numbers. The method public int lowerCommonMultiple(int x1, int x2) solves this problem and I think it can be used in other context.
List of the class methods
All the code is included in the methods of the BestMultiple class. These methods (excluding the main) are:
public int[] removeElem(int[] tensArray, int rm_index): used to remove an element from an array
public int leastCommonMultiple(int x1, int x2): calculates the Least Common Multiple of 2 numbers
private int getLeastCommonMultipleNnumber(int[] arr): Calculates the least common multiple of N-1 integer contain in an array
public int process(int[] arr): calculates the least multiple of exactly N-1 number of an array of N integer; it manages many test strange cases (array empty, elem<=0, etc.)
May be the code is not optimized, but I hope it is correct (the output added, shows that it works correctly, at least with the test cases chosen).
public class BestMultiple {
/*++++++++++++++++++++++++++++++++++++++++++++
Method: removeElem() remove an element from
an array.
+++++++++++++++++++++++++++++++++++++++++++*/
public int[] removeElem(int[] tensArray, int rm_index) {
// Create a proxy array of size one less than original array
int[] proxyArray = new int[tensArray.length - 1];
// copy all the elements in the original to proxy array
// except the one at index
for (int i = 0, k = 0; i < tensArray.length; i++) {
// check if index is crossed, continue without copying
if (i == rm_index) {
continue;
}
// else copy the element
proxyArray[k++] = tensArray[i];
}
return proxyArray;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Method: leastCommonMultiple() Calculates the Least Common
multiple for 2 numbers
++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
public int leastCommonMultiple(int x1, int x2) {
int lcm = 1;
int max = x1;
if ((x1 == 0) || (x2 == 0)) {
lcm = 0;
} else {
if (x2 > x1) {
max = x2;
}
for (int i = 2; i <= max; i++) {
int exp_x1 = 0;
int exp_x2 = 0;
int exp = 0;
if (x1 > 1) {
while ((x1 % i) == 0) {
exp_x1++;
x1 /= i;
}
}
if (x2 > 1) {
while ((x2 % i) == 0) {
exp_x2++;
x2 /= i;
}
}
if ((exp_x1 > 0) || (exp_x2 > 0)) {
exp = exp_x1;
if (exp_x2 > exp) {
exp = exp_x2;
}
while (exp > 0) {
lcm *= i;
exp--;
}
}
}
}
return lcm;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Method: getLeastCommonMultipleNnumber()
Calculates the least common multiple of N-1
integer contain in an array
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
public int getLeastCommonMultipleNnumber(int[] arr) {
int multiple = 1;
if (arr.length >= 2) {
multiple = leastCommonMultiple(arr[0], arr[1]);
for (int j = 2; j < arr.length; j++) {
multiple = leastCommonMultiple(multiple, arr[j]);
}
} else {
// array with only 2 elements
multiple = arr[0];
}
return multiple;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Method: process()
Calculates the least multiple of EXACTLY N-1
number of an array of N integer
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
public int process(int[] arr) {
int answer;
if (arr.length <= 1) {
// array contains only one element or is empty => return -1
answer = -1;
} else {
int pos_elem_zero = -1;
int prod = 1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
prod *= arr[i];
} else {
if (arr[i] < 0) {
// integer < 0 are not allowed
return -1;
}
if (pos_elem_zero == -1) {
pos_elem_zero = i;
} else {
// there are more element == 0
return -1;
}
}
}
if (pos_elem_zero >= 0) {
// there is one element == 0
arr = this.removeElem(arr, pos_elem_zero);
return getLeastCommonMultipleNnumber(arr);
}
// managing of normal test case
answer = prod;
for (int i = 0; i < arr.length; i++) {
int elem = arr[i];
int[] arr2 = this.removeElem(arr, i);
int multiple = getLeastCommonMultipleNnumber(arr2);
if (multiple > elem) {
if ((multiple % elem) != 0) {
if (multiple < answer) {
answer = multiple;
}
}
} else {
if (multiple < elem) {
answer = multiple;
}
}
}
if (answer == prod) {
answer = -1;
}
}
return answer;
}
/*++++++++++++++++++++++++++++++++++++++++++
Method: main() Executes test of process()
method
+++++++++++++++++++++++++++++++++++++++++*/
public static void main(String[] args) {
BestMultiple bm = new BestMultiple();
int[] arr1 = {6,30,5,3};
int[] arr2 = {1,2,3};
int[] arr3 = {1,2,3,3};
int[] arr4 = {6,7,5,3};
int[] arr5 = {9,14, 21};
int[] arr6 = {2,4};
int[] arr7 = {2,3,5};
int[] arr8 = {2,3,6};
int[] arr9 = {2};
int[] arr10 = {};
int[] arr11 = {2,3,0};
int[] arr12 = {0,2,3,0};
int[] arr13 = {20,3};
int[] arr14 = {0,6,15};
int[] arr15 = {1,6,15,-1};
int[] arr16 = {1,6,15};
int[] arr17 = {2,3,0,6,15};
System.out.println("{6,30,5,3} --> " + bm.process(arr1));
System.out.println("{1,2,3} --> " + bm.process(arr2));
System.out.println("{1,2,3,3} --> " + bm.process(arr3));
System.out.println("{6,7,5,3} --> " + bm.process(arr4));
System.out.println("{9,14,21} --> " + bm.process(arr5));
System.out.println("{2,4} --> " + bm.process(arr6));
System.out.println("{2,3,5} --> " + bm.process(arr7));
System.out.println("{2,3,6} --> " + bm.process(arr8));
System.out.println("{2} --> " + bm.process(arr9));
System.out.println("{} --> " + bm.process(arr10));
System.out.println("{2,3,0} --> " + bm.process(arr11));
System.out.println("{0,2,3,0} --> " + bm.process(arr12));
System.out.println("{20,3} --> " + bm.process(arr13));
System.out.println("{0,6,15} --> " + bm.process(arr14));
System.out.println("{1,6,15,-1} --> " + bm.process(arr15));
System.out.println("{1,6,15} --> " + bm.process(arr16));
System.out.println("{2,3,0,6,15} --> " + bm.process(arr17));
}
}
Output of the program
The output of the program with the test cases chosen is:
{6,30,5,3} --> -1
{1,2,3} --> 2
{1,2,3,3} --> 3
{6,7,5,3} --> 30
{9,14,21} --> 42
{2,4} --> 2
{2,3,5} --> 6
{2,3,6} --> -1
{2} --> -1
{} --> -1
{2,3,0} --> 6
{0,2,3,0} --> -1
{20,3} --> 3
{0,6,15} --> 30
{1,6,15,-1} --> -1
{1,6,15} --> 6
{2,3,0,6,15} --> 30
You start by writing a method process that computes the minimum number for each subarray with one element excluded:
public static int process(int... arr) {
int min = -1;
for (int i = 0; i < arr.length; ++i) {
int r = process(arr, i);
if (r != -1) {
if (min == -1) {
min = r;
} else {
min = Math.min(min, r);
}
}
}
return min;
}
Where the second process method looks like this:
private static int process(int[] arr, int exclude) {
int result = 0;
for (int i = 0; i < arr.length; ++i) {
if (i != exclude) {
if (result == 0) {
result = arr[i];
} else {
result = lcm(result, arr[i]);
}
}
}
if (result%arr[exclude] == 0) {
return -1;
}
return result;
}
You need a method that computes the LCM of two numbers. Here, I'll use a second method that computes the GCD:
private static int lcm(int a, int b) {
return a*b/gcd(a,b);
}
private static int gcd(int a, int b) {
if (a == 0) {
return b;
} else if (b == 0) {
return a;
} else {
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return a;
}
}
Examples:
System.out.println(process(2, 3, 5)); // prints 6
System.out.println(process(2, 3, 6)); // prints -1
System.out.println(process(9, 14, 21)); // prints 42 (divisible by 14 and 21, but not by 9
System.out.println(process(6, 7, 5, 3)); // prints 30 (divisible by 6, 5, 3, but not by 7
The way you implemented process() assumes the input array is sorted. But anyway, I don't think sorting will help here. Note that the number satisfying the given conditions can be divided by the biggest number. For [2, 3, 5, 6] it is 6. Dividing the product of all the elements by consecutive elements from the biggest to the lowest and stopping at the first that is not a divisor is also not correct. In the example [2, 4, 5, 6] this would give 2 * 4 * 5 = 40 when the correct answer is 20.
My idea is to use an algorithm inspired by Sieve of Eratosthenes. Note that the number that satisfies the conditions can't be bigger than the product of all the elements. So create a table divisors[] with indices from 0 through the product of the elements of array where divisors[i] indicates how many elements from array divide i. Iterate over elements of array and increment all elements in divisors[i] where i is divided by the element. Then find the first i for which divisors[i] == n - 1.
The limitation is that divisors can be quite big depending on what is the product of array, so applicability will be limited to relatively small values in array.
My code runs but for one of the tests two outputs are printed when I only need one. I am unsure of how to avoid this.
This is the task:
Write an application that displays every perfect number from 2 through 1,000. A perfect number is one that equals the sum of all the numbers that divide evenly into it. For example, 6 is perfect because 1, 2, and 3 divide evenly into it and their sum is 6; however, 12 is not a perfect number because 1, 2, 3, 4, and 6 divide evenly into it, and their sum is greater than 12.
The provided template lays out the initial for loop to check each number beginning from 2 and going up to 1,000. In this for loop, the perfect() method is called, where you will submit your piece of code to test if each number follows the conditions described above.
Set result to true if it meets those conditions and use sum to add up the numbers divisible by int n in the method's parameter.
public class Perfect{
public static void main (String args[]){
final int MAX = 1000;
for(int i = 2; i <= MAX; i++)
if(perfect(i) == true)
System.out.println("The number " + i + " is perfect");
}
public static boolean perfect(int n){
int sum = 1;
int i;
boolean result = false;
for (i = 2; i < n / 2; i++) {
if (n % i == 0) {
sum += i;
}
}
if (sum == i) {
return true;
}
else {
return false;
}
}
}
My output:
The number 496 is perfect
The number 729 is perfect
Expected output:
The number 496 is perfect
It only expects the first line printed...
You need to compare sum to the original number n, not to i. And you need to add 1 to the loop condition or it will miss the last divider in even numbers
public static boolean perfect(int n){
int sum = 1;
for (int i = 2; i < (n / 2) + 1; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum == n;
}
First, I don't know if you have used the correct formula. But, you should know that the first perfect number are 6, 28, 496 and 8128. 729 is not a perfect number.
Hope it helped.
public static void main(String[] args) {
int i, j, s;
System.out.println("Perfect numbers 1 to 1000: ");
for(i=1;i<=1000;i++){
s=0;
for(j=1;j<i;j++){
if(i%j==0){
s=s+j;
}
}
if(i==s){ //if i == s is perfect
System.out.println(i);
}
}
}
}
According to the question, you have to print all perfect numbers.
I have created a small snippet, try it and see.
public void printPerfect() {
for(int i=2;i<1000;i++) {
List<Integer> l =factors(i);
int sum =0;
for (Integer factor : l) {
sum+=factor;
}
if(sum==i) {
System.out.println("perfect-- " +i);
}
}
}
List<Integer> factors(int number) {
List<Integer> l = new ArrayList<Integer>();
for(int i = 1; i <= number; ++i) {
if (number % i == 0) {
if(i!=number)
l.add(i);
}
}
return l;
}
You checked sum == i instead of sum == n.
As 729 = 3^6 : 3, 243, 9, 81, 27.
public static boolean perfect(int n) {
int sum = 1;
for (int i = 2; i <= n / 2 && sum <= n; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum == n;
}
In our directions, we have to get a 16 digit number, then sum all the digits in the odd place from right to left. After that, we have to sum all the even place digits from right to left, double the sum, then take module 9. When I try to run my code, I keep getting "Invalid", even if it is with a valid credit card number.
public static boolean validateCreditCard(long number) {
double cardSum = 0;
for (int i = 0; i < 16; i++) {
long cardnumber = (long) Math.pow(10, i);
double oddPlaceSum = 0;
double evenPlaceSum = 0;
if (i % 2 != 0) {
oddPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i))));
} else { // so if i%2 ==0
evenPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i)) * 2 % 9));
}
cardSum += evenPlaceSum + oddPlaceSum;
}
if (cardSum % 10 == 0) {
return true;
System.out.println("Valid");
} else {
return false;
System.out.println("Invalid");
}
}
Try this instead :
Convert the 16 digit number into a String using Long.toString(number).
Iterate through the String character by character and keep track of even and odd indexes.
Convert each char to an Integer using Integer.valueOf() thereby adding them incrementally.
Voila, you got your evenSum and oddSum. Next steps should be trivial.
public static boolean validateCreditCard(long number){
String x = Long.toString(number);
int evenSum = 0;
int oddSum = 0;
for(int i=0; i<x.length; i=i+2) {
oddSum += Integer.valueOf(s[i]);
evenSum += Integer.valueOf(s[i+1]);
}
//Do the next steps with odd and even sums.
Also, do handle IndexOutOfBoundsException as appropriate.
You can do it in a single while loop as digits are fixed, like this:
int digit,evensum,oddsum;
int i=16;
while(i > 0){
digit=number%10;
if(i%2 == 0)
evensum+=digit;
else
oddsum+=digit;
i--;
digit/=10;
}
Try this instead
using Recusion find sum of even placed of digit and sum of odd placed of digit.
class Recursion {
static int count = 0;
static int even =0;
static int odd =0;
public static int Digits(int num) {
if (num > 0) {
count++;
if(count%2 == 0){
even += num%10;
}
else{
odd += num%10;
}
Digits(num / 10);
}
return even;
// for odd
// return odd;
}
public static void main(String[] args) {
int num = 31593;
int res = Digits(num);
System.out.println("Total digits are: " + res);
}
}
Help me How to print both even and odd sum together?
What I am trying to do should be pretty easy, but as I'm new to java, I'm struggling with what might be basic programming.
The main issue is how to check if the (x+1) number of an integer is greater than the x number, which I am trying to do as follow :
for( int x=0; x < Integer.toString(numblist).length();x++) {
if (numblist[x] < numblist[x+1]) {
compliance= "OK";
} else{
compliance="NOK";
}
But it returns an error "array required but integer found".
It seems to be a basic type mistake, which might come from the previous step (keeping only the numbers included in a string):
for (int p = 0; p < listWithoutDuplicates.size(); p++) {
Integer numblist = Integer.parseInt(listWithoutDuplicates.get(p).getVariantString().replaceAll("[\\D]", ""));
I can't find the answer online, and the fact that it shouldn't be complicated drives me crazy, I would be grateful if someone could help me!
Do the reverse. If they are increasing starting from the first digit, it means that they are decreasing from the last to the first. And it is much easier to program this way:
public boolean increasingDigits(int input)
{
// Deal with negative inputs...
if (input < 0)
input = -input;
int lastSeen = 10; // always greater than any digit
int current;
while (input > 0) {
current = input % 10;
if (lastSeen < current)
return false;
lastSeen = current;
input /= 10;
}
return true;
}
You can't index an integer (i.e. numblist) using the [] syntax -- that only works for arrays, hence your error. I think you're making this more complicated than it has to be; why not just start from the back of the integer and check if the digits are decreasing, which would avoid all this business with strings:
int n = numblist;
boolean increasing = true;
while (n > 0) {
int d1 = n % 10;
n /= 10;
int d2 = n % 10;
if (d2 > d1) {
increasing = false;
break;
}
}
One way I could think of was this:
boolean checkNumber(int n) {
String check = String.valueOf(n); // Converts n to string.
int length = check.length(); // Gets length of string.
for (int i = 0; i < length-1; i++) {
if(check.charAt(i) <= check.charAt(i+1)) { // Uses the charAt method for comparison.
continue; // if index i <= index i+1, forces the next iteration of the loop.
}
else return false; // if the index i > index i+1, it's not an increasing number. Hence, will return false.
}
return true; // If all digits are in an increasing fashion, it'll return true.
}
I'm assuming that you're checking the individual digits within the integer. If so, it would be best to convert the Integer to a string and then loop though the characters in the string.
public class Test {
public static void main(String[] args) {
Integer num = 234; // New Integer
String string = num.toString(); // Converts the Integer to a string
// Loops through the characters in the string
for(int x = 0; x < string.length() - 1; x++){
// Makes sure that both string.charAt(x) and string.charAt(x+1) are integers
if(string.charAt(x) <= '9' && string.charAt(x) >= '0' && string.charAt(x+1) <= '9' && string.charAt(x+1) >= '0'){
if(Integer.valueOf(string.charAt(x)) < Integer.valueOf(string.charAt(x+1))){
System.out.println("OK");
}else{
System.out.println("NOK");
}
}
}
}
}
I think a simple way could be this
package javacore;
import java.util.Scanner;
// checkNumber
public class Main_exercise4 {
public static void main (String[] args) {
// Local Declarations
int number;
boolean increasingNumber=false;
Scanner input = new Scanner(System.in);
number = input.nextInt();
increasingNumber = checkNumber(number);
System.out.println(increasingNumber);
}
public static boolean checkNumber(int number) {
boolean increasing = false;
while(number>0) {
int lastDigit = number % 10;
number /= 10;
int nextLastDigit = number % 10;
if(nextLastDigit<=lastDigit) {
increasing=true;
}
else {
increasing=false;
break;
}
}
return increasing;
}
}
private boolean isIncreasingOrder(int num) {
String value = Integer.toString(num);
return IntStream.range(0, value.length() - 1).noneMatch(i -> Integer.parseInt(value.substring(i, i + 1)) > Integer.parseInt(value.substring(i + 1, i + 2)));
}
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);
}