using methods to sum up numbers digits - java

This code is designed for summing up the digits of the number but it brings up
javac Root.java Root.java:17: error: '.class' expected
Who can explain what is the problem here. Also i want to make the same program using Arrays but i have problems with putting int in Array, if you have suggestions i am glade to here you.
import java.util.Scanner;
class Root {
public static int numRoot(int n, int sum){
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
public static void main(String[] args){
int sum = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number here");
int n = in.nextInt();
int root = numRoot(int sum, int n);
System.out.print("the sum of the digits off given num is " + root);
}
}

You have error here, Correct it.
int root = numRoot(int sum, int n); // this is wrong
Change it to
int root = numRoot(n,sum); // should use correct order of input parameters

This should be your method, you do not need to pass sum:
public static int numRoot(int n){
int sum=0;
while (n != 0) {
sum += n % 10;
n = n / 10;
}
return sum;
}
and you shall call it like this:
int root = numRoot(n);

Related

How to write a strong number function in Java

enter image description hereI am trying to solve this question:
a) Write a method with the following header that takes an integer n and
returns the value of n! (pronounced n factorial) computed as follows:
public static int factorial(int n)
Note that 0! = 1 and n! = n * (n-1) * (n-2)*.....*1.
Example: factorial(4) will return 24 which is = 4*3*2*1.
b) Write a method with the following header that takes an integer x and
returns true if x is a Strong number. Otherwise, it returns false.
public static boolean isStrongNumber(int x)
Note that the isStrongNumber method should call the factorial method to compute the factorial of
each digit in x.
public static int factorial(int n) {
int f =1;
for (int i = 1; i <=n; i++)
f=f*i;
return f;
}
public static boolean isStrongNumber(int x) {
int temp = x;
int z;
int q = 0;
int sum = 0;
while (temp > 0) {
x = x % 10;
z = factorial(x);
q += z;
if (q == temp) {
System.out.print(q + " ");
return true;
}
}
}
This is my answer, but I get an error every time I try to run it.
You did not return boolean value at end of the isStrongNumber method
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static boolean isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
sum += factorial(num % 10);
num /= 10;
}
return sum == originalNum;
}
, main function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = Integer.parseInt(scanner.nextLine());
Set<Integer> set = new TreeSet<>();
for (int i = 1; i <= number; i++) {
if (isStrongNumber(i)) {
set.add(i);
}
}
System.out.println("The Strong numbers between 1 and " + number + " are:");
System.out.println(set);
scanner.close();
}
, output for input 100000
Enter a positive integer: 100000
The Strong numbers between 1 and 100000 are:
[1, 2, 145, 40585]
This cannot compile as it lacks a return statement outside the while loop. In fact, you cant be sure to go inside the loop even once if x<=0 for exmaple. You should add return false outside the loop at the end of the method. Also if you get an error and write a question on StackOverflow, copy the error message it's very helpful.

Why is the first one cannot be executed?? and if i want to use the first one what should i add?? is it sum = (long) sum + n % 10; ? HELP MEEEEE

import java.util.Scanner;
public class Exercise33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
long n = input.nextLong();
System.out.println("The sum of the digits is: " + sumDigits(n));
}
public static long sumDigits(long n) {
int sum = 0;
while (n != 0) {
long sum = sum + n % 10;
n = n/10;
}
return sum;
}
}
import java.util.Scanner;
public class Exercise33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
long n = input.nextLong();
System.out.println("The sum of the digits is: " + sumDigits(n));
}
public static int sumDigits(long n) {
int sum = 0;
while (n != 0) {
sum += n % 10;
n /=10;
}
return sum;
}
}
Why is the first one cannot be executed?? and if i want to use the first one what should i add?? is it sum = (long) sum + n % 10; ? HELP MEEEEE
Take a look at
public static long sumDigits(long n) {
int sum = 0;
while (n != 0) {
long sum = sum + n % 10;
n = n/10;
}
return sum;
}
You have 2 variables named "sum" in the same scope.
int sum, long sum.
Why you have sum deklaret with int? The parameter from the sumDigits method has the datatype long. So change the datatype from sum in the methode from int to long. Then you must declare the sum in the while no more.
I hope this is what you searching for, otherwise you must ask your question more clearly where the problem is...
First Example:
public static long sumDigits(long n) {
long sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n/10;
}
return sum;
}

Finding the sum of multiples of any number less than the specified number. Where is my mistake?

This is my another solution where the output is shown as expected
public class Logic2 {
public static void main(String[] args) {
long sum = 0;
calculation key = new calculation();
sum = key.sum(3, 1000);
System.out.print(sum);
}
}
class calculation {
long total = 0;
public long sum(int num, int limit) { //multples of num less than limit
int number = Integer.valueOf(limit / num);
if (limit % num == 0) {
number -= 1;
}
total = (number / 2) * (2 * num + (number - 1) * num);
return total;
}
}
I wrote this code myself. It seems everything fine but I am not getting the required output. Why is this so?
It looks like your math is just slightly wrong. Try breaking it up into smaller parts to confirm you're getting what you're expecting. A working example which returns 166833
public static void main(String[] args) {
int a = 3, N = 1000;
System.out.println("Sum of multiples of " + a +
" up to " + N + " = " +
calculate_sum(a, N));
}
private static int calculate_sum(int a, int N) {
// Number of multiples
int m = N / a;
// sum of first m natural numbers
int sum = m * (m + 1) / 2;
// sum of multiples
return a * sum;
}
If you split your method up the same way, you will see where you've missed the mark slightly.
public class Logic2 {
public static void main(String[] args) {
long sum = 0;
calculation key = new calculation();
sum = key.sum(3, 1000);
System.out.print(sum);
}
}
class calculation {
long total = 0;
public long sum(int num, int limit) { //multples of num less than limit
int number = Integer.valueOf(limit / num);
if (limit % num == 0) {
number -= 1;
}
total=((number)*(2*num+(number-1)*num))/2;
//previouslly total = (number / 2) * (2 * num + (number - 1) * num);
return total;
}
}
I figured out the bug myself. In that, Total if we write (number/2) then it will give integer value due to which I was not getting the required output. Anyways, Thanks everyone for at list viewing my post, I appreciate it. :)

Why java method is not working in loop

This is code to find armstorm numbers between given intervals. But when I put my my method in loop in main method so that it can run between given interval, then the loop only run one time and don't change the value passed to method. Why this is so? Is there is a difference in working of these conditions in different languages?
import java.util.Scanner;
class ArmstormNumbers {
int mod, div, count = 0, rev = 0, pow = 1, sum = 0;
int checkArm(int num) {
while(num!=0) {
mod = num%10;
div = num/10;
num = div;
count++;
rev = (rev*10) + mod;
}
while(rev!=0) {
mod = rev%10;
div = rev/10;
rev = div;
int temp = mod;
for(pow = 1; pow < count; pow++) {
mod = mod * temp;
}
sum=sum+(mod);
}
return sum;
}
}
class HelloWorld {
public static void main(String args[]) {
int num, arms, inp, fp, asm, num2;
Scanner input = new Scanner(System.in);
ArmstormNumbers object = new ArmstormNumbers();
System.out.println("This program will find armstorm numbers between two intervels");
System.out.println("Input Initial point ");
num = input.nextInt();
System.out.println("Input Final Point");
num2 = input.nextInt();
int temp = num;
for(num = temp; num <= num2; num++) {
asm = object.checkArm(num);
if(asm == num) {
System.out.println(num);
}
}
}
}
Move the variable declarations so that they become method-local variables which get initialised each time the method is executed, instead of only once when instantiating the object.
I.e. change
int mod,div,count=0,rev=0,pow=1,sum=0;
int CheckArm(int num)
{
to
int CheckArm(int num)
{
int mod,div,count=0,rev=0,pow=1,sum=0;
The problem you have and which you solve that way is probably relying on sum being 0 at start but not making that sure.

Calculating Digital Root, is there a better way?

This is how i calculated the digital root of an integer.
import acm.program.*;
public class Problem7 extends ConsoleProgram
{
public void run()
{
println("This program calculates the digital root of an interger.");
int num = readInt("Enter the number: ");
int sum = 0;
while (true)
{
if (num > 0)
{
int dsum = num % 10;
num /= 10;
sum += dsum;
}
else if (sum > 9)
{
int dsum = sum % 10;
sum /= 10;
sum += dsum;
} else if (sum <= 9 ) break;
}
println("Digital Root is: " + sum);
}
The program works fine.
Is there a better/shorter way of calculating the digital root of a number. ?
EDIT/ADDED : Here is the implementation of the above problem by using Tyler's answer, it works as well:
import acm.program.*;
public class Problem7 extends ConsoleProgram
{
public void run()
{
println("This program calculates the digital root of an interger.");
int num = readInt("Enter the number: ");
println("Digital Root of " + num + " is: " + (1 + (num - 1) % 9));
}
}
#include <stdio.h>
int main(void)
{
int number;
scanf("%d", &number);
printf("The digital root of %d is %d.", number, (1 + (number - 1) % 9));
}
Had I not been able to find Ramans' formula this is how I would write this program...:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int c;
int number = 0;
while ((c = getchar()) != EOF)
{
if (isdigit(c))
number += (c - '0');
}
if (number <= 9)
{
printf("The digital root is %d\n", number);
}
else
{
printf("%d", number);
}
}
After compiling, to run this, basically you just chain these together. I believe four is the most you could possibly need for an integer.
$ echo 829382938 | ./digitalroot | ./digitalroot | ./digitalroot | ./digitalroot
Personally, I do not like your loop, which is essentially two loops (first going over the original digits, then going over the digits of sum) mashed into one. How about a sprinkling of recursion:
private int sumDigits(int in){
if (i>10)
return in%10 + sumDigits(in/10);
return in;
}
private int digitalRoot(int in){
assert (in > 0) ;
while (in > 9) in=sumDigits(in);
return in;
}
I think I am at the same point in the class, no recursion or any moderately advanced ideas (I'm a super beginner). I used
public void run() {
println("This program finds the digital root of an integer.");
int n = readInt("Enter a positive integer: ");
int dsum = 0;
while (n>0) {
dsum += n % 10;
n /= 10;
if ((n==0) && (dsum>9)) {
n = dsum;
dsum = 0;
}
}
println("The digital root of the integer is " + dsum);
}
Wolfram Alpha is amazing. It pretty much spoon fed me the follow solution:
int getDigitalRoot(int n, int base){
return (1+(n-1)%base); }
int getDigitalRoot(int n){
return (1+(n-1)%9); }
This is a O(1) solution, no loops, or recursion necessary.
I would take the input in as a String instead. This way, you can simply loop through the String and use Integer.parseInt() to grab each number and add them. You can convert that number again to a String and loop through the code to obtain your digital root.
public void run()
{
println("This program calculates the digital root of an interger.");
String num = readLine("Enter the number: ");
int sum = 10;
while (num > 9) {
for (int x = 0; x < num.length(); x++) {
sum = Integer.parseInt(num.charAt(x));
}
num = Integer.toString(sum);
}
println("Digital Root is: " + sum);
}
public static void main(String[] args)
{
int n;
Scanner scan=new Scanner(System.in);
System.out.println("Enter the no. of which you want to find the digital root");
n=scan.nextInt();
System.out.println(n%9);
}
Here is the shortest solution I have found that works for all use cases.
public int digRoot(int num) {
num = 1015; {
return (1+(num-1)%9);
}
}
ref: https://dgeekspot.wordpress.com/2015/11/17/digital-root-algorithm/
My solution is in C# and there is kinda stuff that is useless but I hope that will help you.
using System.Linq;
using System;
public static int DigitalRoot(long n)
{
long sum = 0;
if (n <= 10) return n == 10 ? 1 : Convert.ToInt32(n);
while (n != 0)
{
sum += (n % 10);
n /= 10;
}
return sum > 9 ? DigitalRoot(sum) : Convert.ToInt32(sum);
}

Categories