这是我想要解决的编程问题:2520是可以除以1到10之间的每个数字而没有任何余数的最小数字。
从1到20的所有数字均可被整除的最小正数是多少?
到目前为止,这是我的解决方案,但是每次答案都是零,所以我认为我的代码中有错误。任何帮助将不胜感激。
public static boolean isDiv(int num){
boolean isDiv = false;
for (int i = 1; i <= 20; i++){
if (i == 20){
isDiv = true;
}
if ((num % i) == 0){
continue;
}
else {
break;
}
}
return isDiv;}
public static int smallMulti(int num){
boolean div = isDiv(num);
int answer = 0;
for (int i = num; num < 2520; i--){
if (div = true){
answer = i;
}
}
return answer;}
答案 0 :(得分:2)
你整个问题过于复杂,加上多个逻辑错误。基本上你只需要2个循环。这是一个代码,用于检查每个数字所需的第一个数字,直到Integer.MAX_VALUE
。如果你想要更高,你可以采用代码来使用long
。
public static int smallMulti(int num) {
for (int i = 1; num <= Integer.MAX_VALUE; ++i) { // Check every int in the scope of the Integer
for (int j = 2;j<=num;++j) {
if(i % j != 0) {
break; // If i % j is unequal to 0 then this number isn´t valid.
}
if(j == num) {
return i; // If we reached j == num then everything was divisble yet so we can return i as the correct value;
}
}
}
return -1;
}
这是主要
的示例输出public static void main(String[] args) {
for(int i = 2; i <= 20; ++i)
System.out.println("Smallest Value divisible by 1-"+ i + " = " + smallMulti(i));
}
OutPut
Smallest Value divisible by 1-2 = 2
Smallest Value divisible by 1-3 = 6
Smallest Value divisible by 1-4 = 12
Smallest Value divisible by 1-5 = 60
Smallest Value divisible by 1-6 = 60
Smallest Value divisible by 1-7 = 420
Smallest Value divisible by 1-8 = 840
Smallest Value divisible by 1-9 = 2520
Smallest Value divisible by 1-10 = 2520
Smallest Value divisible by 1-11 = 27720
Smallest Value divisible by 1-12 = 27720
Smallest Value divisible by 1-13 = 360360
Smallest Value divisible by 1-14 = 360360
Smallest Value divisible by 1-15 = 360360
Smallest Value divisible by 1-16 = 720720
Smallest Value divisible by 1-17 = 12252240
Smallest Value divisible by 1-18 = 12252240
Smallest Value divisible by 1-19 = 232792560
Smallest Value divisible by 1-20 = 232792560
答案 1 :(得分:2)
我使用lcm(最小公倍数)实现
public static int lcm(int a, int b) {
return (a*b)/gcd(a, b);
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static int smallMulti(int n) {
int number = 1;
for (int i = 2; i <= n; i++) {
number = lcm(number, i);
}
return number;
}