+ 2

вернуть кратные Х числу )

Implement method findMultiples(x, n) which returns an array of the first x multiples of the real number n.

11th Mar 2021, 3:37 PM
Anton
Anton - avatar
7 Answers
+ 1
You don't necessarily need to check if the number is divisible by another number to find multiples. For example, let's find the multiples of 10. So an efficient for loop should look like this - n = 10; x = no. of multiples for(int i = n; i < x; i += n) {} In the first iteration, i = 10. In the 2nd, i = 20, since 10 + 10 = 20 and so on. Now getting back to storing the mutliples, you can have a counter variable with an initial value of zero for that. At every iteration of the for loop, you use that counter variable as index and increment it. https://code.sololearn.com/cqavCQ9K9fhZ/?ref=app
11th Mar 2021, 4:44 PM
Soumik
Soumik - avatar
+ 1
wow thx ♥
11th Mar 2021, 4:50 PM
Anton
Anton - avatar
+ 1
public static int[] findMultiples(int x, int n) { int[] resArr = new int[x]; int cnt = 0; for(int i = 2; i <= (int) Math.sqrt(n); i++) { if(n%i == 0) { resArr[cnt] = i; cnt++; } if(cnt==x-1) return resArr; } return resArr; }
11th Mar 2021, 5:09 PM
Igor Kostrikin
Igor Kostrikin - avatar
0
Hello. I am trying to solve through "foreach" and "if" but can not figure out how to fill the returned array with multiples of X
11th Mar 2021, 4:09 PM
Anton
Anton - avatar
0
Anton Can you show us your code please?
11th Mar 2021, 4:10 PM
Soumik
Soumik - avatar
0
Anton I hope I was able to explain properly. If not, feel free to ask any questions 😊. Happy Coding!
11th Mar 2021, 4:53 PM
Soumik
Soumik - avatar
- 1
public static void main(String[] args) { int x = 3; int n = 4; int[] myArray = new int[x]; for(int i= 0; i<myArray.length;i++){ if(myArray[i]%x == 0){ myArray[i] +=n; } System.out.println(myArray[i]); } } supposably x =3,n=4; trying to make index of array like X times to + by itself
11th Mar 2021, 4:35 PM
Anton
Anton - avatar