Here is the programming problem i am trying to solve: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
Here is my solution so far, however the answer comes up as zero everytime so i think i have an error in my code. Any help would be appreciated.
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;}
You are overcomplicating the whole problem, combined with multiple logical mistakes. Basicly you just need 2 loops. Here´s a the code checking for the first number beeing devisible by every number until Integer.MAX_VALUE. If you want to go higher you could adopt the code to work with 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;
}
Heres the example output for this main
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
I implemented with lcm(least common multiple)
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;
}
Related
I am still somewhat of a beginner to Java, but I need help with my code. I wanted to write an Armstrong Number checker.
An Armstrong number is one whose sum of digits raised to the power three equals the number itself. 371, for example, is an Armstrong number because 3^3 + 7^3 + 1^3 = 371.
If I understand this concept correctly, then my code should work fine, but I don't know where I made mistakes. I would appreciate if you could help correct my mistakes, but still kind of stick with my solution to the problem, unless my try is completely wrong or most of it needs to change.
Here is the code:
public class ArmstrongChecker {
boolean confirm = false;
Integer input;
String converter;
int indices;
int result = 1;
void ArmstrongCheck(Integer input) {
this.input = input;
converter = input.toString();
char[] array = converter.toCharArray();
indices = array.length;
result = (int) Math.pow(array[0], indices);
for (int i = 1; i < array.length; i++) {
result = result + (int) Math.pow(array[i], indices);
}
if (result == input) {
confirm = true;
System.out.println(confirm);
} else {
System.out.println(confirm);
}
}
}
For my tries I used '153' as an input. Thank you for your help!
You aren't summing the digits, but the numeric values of the characters representing them. You can convert such a character to its numeric value by subtracting the character '0':
int result = 0;
for(int i = 0; i < array.length; i++) {
result = result + (int) Math.pow(array[i] - '0', indices);
}
Having said that, it's arguably (probably?) more elegant to read the input as an actual int number and iterate its digits by taking the reminder of 10 on each iteration. The number of digits itself can be calculated using a base-10 log.
int temp = input;
int result = 0;
int indices = (int) Math.log10(input) + 1;
while (temp != 0) {
int digit = temp % 10;
result += (int) Math.pow(digit, indices);
temp /= 10;
}
There is a small logical mistake in your code, You're not converting the character to an integer instead you're doing something like
Math.pow('1', 3) -> Math.pow(49, 3) // what you're doing
Math.pow(1, 3) // what should be done
You should first convert the character to the string using any method below
result = (int) Math.pow(array[0],indices);
for(int i = 1;i<array.length;i++) {
result = result + (int) Math.pow(array[i],indices);
}
For converting char to integer
int x = Character.getNumericValue(array[i]);
or
int x = Integer.parseInt(String.valueOf(array[i]));
or
int x = array[i] - '0';
Alternatively
You can also check for Armstrong's number without any conversion, using the logic below
public class Armstrong {
public static void main(String[] args) {
int number = 153, num, rem, res = 0;
num = number;
while (num != 0)
{
rem = num % 10;
res += Math.pow(rem, 3);
num /= 10;
}
if(res == num)
System.out.println("YES");
else
System.out.println("NO");
}
}
For any int >= 0 you can do it like this.
Print all the Armstrong numbers less than 10_000.
for (int i = 0; i < 10_000; i++) {
if (isArmstrong(i)) {
System.out.println(i);
}
}
prints
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
The key is to use Math.log10 to compute the number of digits in the candidate number. This must be amended by adding 1. So Math.log10(923) returns 2.965201701025912. Casting to an int and adding 1 would be 3 digits.
The number of digits is then the power used for computation.
Then it's just a matter of summing up the digits raised to that power. The method short circuits and returns false if the sum exceeds the number before all the digits are processed.
public static boolean isArmstrong(int v) {
if (v < 0) {
throw new IllegalArgumentException("Argument must >= 0");
}
int temp = v;
int power = (int)Math.log10(temp)+1;
int sum = 0;
while (temp > 0) {
sum += Math.pow(temp % 10, power);
if (sum > v) {
return false;
}
temp/= 10;
}
return v == sum;
}
For a given number N(0<N<=100) find out the minimum positive integer X divisible by N, where the sum of digits of X is equal to N, and X is not equal to N.
public static int getSmallestNumber(int input1) {
int res =0;
for(int i=2;i<10000;i++) {
if(getSum(input1*i) == input1) {
res = input1*i;
break;
}
}
return res;
}
static int getSum(int n) {
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n/10;
}
return sum;
}
Example: Input: 9
output: 18
Explanation: 1+8 is 9 and 18 is divisible by 9
Example2: Input: 10
output: 190
Explanation: 1+9+0 is 10 and 190 is divisible by 10
My solution works for smaller integer but breaks for larger numbers like 98, 99 or 100.
we need to know that if we multiply multiple of 7, 35(3+5=8) with 7 again then obviously a larger number 42(4+2=6) comes but have lower sum of digits so the change in digits with each multiplication seems uncertain. So, if we can find a way to generalize this change in digits of upcoming next to next larger multiples of our number then a time efficient solution can be designed.
I think you need to add the actual check on the condition (i % input1 == 0) to check the divisibility.
public static int getSmallestNumber (int input1) {
int res = 0;
for (int i = input1; i < 10000; i++) {
if (getSum(i) == input1 && i % input1 == 0) {
res = i;
break;
}
}
return res;
}
static int getSum (int n) {
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n/10;
}
return sum;
}
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;
}
Maximum remainder
You are given a number N. Write a program to find a natural number that is smaller than N such that N gives the highest remainder when divided by that number.
If there is more than one such number, print the smallest one.
Can anyone help I think I'm missing something like if 2 numbers will have same reaminders my code would overwrite the minDivisor to the upper value
static int findRemainder(int num){
int maxRemainder=0;
int minDivisor=0
int answer=0;
for(int i = 1; i<num; i++){
if(maxRemainder <= (num % i)) {
maxRemainder = num % i;
if(minDivisor < i && maxRemainder == num%i) {
} else {
minDivisor = i;
}
}
return minDivisor;
}
}
Check this out:
int largestRemainder = c % ((c/2) + 1);
Write a program that prompts the user for an integer and then prints out all prime numbers up to that integer. For example, when the user enters 20, the program should print
2 3 5 7 11 13 17 19
Recall that a number is a prime number if it is not divisible by any number except 1 and itself.
I am trying to write this program but I am having difficulties, can anyone show me how to write this code?
This is what I have written but it is completely wrong.
import java.util.Scanner;
public class PrimeNumbers
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Integers: ");
int x;
int n = in.nextInt();
for (int i = 2; i < n ; i++)
{
x = i;
if (n % i != 0 && i % x != 0)
{
System.out.println(i);
}
x--;
}
}
}
Computes the number of primes less than or equal to N using
the Sieve of Eratosthenes.
% java PrimeSieve 25
The number of primes <= 25 is 9
% java PrimeSieve 100
The number of primes <= 100 is 25
% java -Xmx100m PrimeSieve 100000000
The number of primes <= 100000000 is 5761455
% java PrimeSieve -Xmx1100m 1000000000
The number of primes <= 1000000000 is 50847534
The 110MB and 1100MB is the amount of memory you want to allocate
to the program. If your computer has less, make this number smaller,
but it may prevent you from solving the problem for very large
values of N.
class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]){ primes++; System.out.print(i+", ");}
}
System.out.println("\nThe number of primes <= " + N + " is " + primes);
}
}
Use this method to check if a given int is a prime.
public static boolean isPrime(int a)
{
if ( a == 2)
return true;
int midpoint = Math.round(a/2);
for(int i = 2; i < midpoint; i++)
{
if(a % i == 0)
return false;
}
return true;
}
Explanation:
Loop through all the numbers until midpoint and modulus until you encounter 0 or not. If you encounter 0 then return false because we know that it is not prime, if we encounter no zero then we return true because it is prime.
We loop until midpoint because there is no need to loop further.
You can implement it in your loop via
for (int i = 2; i < n ; i++)
{
if (isPrime(i))
{
System.out.println(i);
}
}