I applied all of my brain but can't figure out what to do for making a program, that finds out whether a number is kaprekar or not by using only 2 functions int countdDigits(int ) and void check(int ) except main(), display the correct result
import java.util.*;
class kaprekar
{
private int countDigit(int a)
{
int count = 0;
while(a>0)
{
a/=10;
++count;
}
return count;
}
private void check(int n)
{
int a = countDigit(n);
int d = (int)Math.pow(10, a);
int sum = (a/d) + (a%d);
if(n==sum)
System.out.println("It is a kaprekar number");
else
System.out.println("It is not a kaprekar number");
}
public static void main()
{
Scanner sc=new Scanner(System.in);
kaprekar ob=new kaprekar();
System.out.println("Enter a number to check");
int num = sc.nextInt();
ob.check(num);
}
}
required result:
Enter a number to check
45
It is a kaprekar number
actual results:
Enter a number to check
45
It is not a kaprekar number
I think your problem is here
int a = countDigit(n);
int d = (int)Math.pow(10, a);
int sum = (a/d) + (a%d);
You divided the number of digits with d. I think you need to divide n with d, not a.
For Kaprekar you have to check if a sum of parts of the square number in question is the same as the number.
e.g. 45 --> 45²=2025 --> 20+25=45
following should do:
import java.util.Scanner;
public class KaprekarCheck {
private static boolean isKaprekar(int n)
{
String square = Long.toString(n*n);
for (int i=1; i< square.length(); i++) {
System.out.println("i="+i+" len="+square.length());
int num1 = Integer.parseInt(square.substring(0, i));
int num2 = Integer.parseInt(square.substring(i, square.length()));
System.out.println("i="+i+" len="+square.length()+" num1="+num1+" num2="+num2);
if (num1+num2==n) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int num = 9;
if(isKaprekar(num))
System.out.println("It is a kaprekar number");
else
System.out.println("It is not a kaprekar number");
}
}
Related
I'm trying to print the sum of digits of the numbers that the user inputs,
what's wrong in my code? it appears to me that sum is underlined in the S.O.P..
but why is that? and how can I fix it?
package assignment7;
import java.util.Scanner;
public class Assignment7_4_5 {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.print("Enter a number: ");
int number=input.nextInt();
System.out.println("sum: "+sumDigits (sum));
}
public static int sumDigits(int sum) {
int number = 0;
while (number > 0) {
sum = sum + number % 10;
number = number / 10;
}
return sum;
}
}
You need to change sumDigits(sum) to sumDigits(number) because number is the variable that you are passing to the method, the variable sum is not even declared before using the method sumDigits. Also in the function, the while loop will never execute because number is set to zero and the condition is (number > 0) which is never true.
You have sum and number the wrong way around. You need to pass in number, as this is what you get from the user. Sum needs to be initialised to 0 in sumDigits, not number. Then you're incrementing sum and dividing down number, returning sum once you're finished. You also don't then skip over your while loop!
package assignment7;
import java.util.Scanner;
public class Assignment7_4_5 {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.print("Enter a number: ");
int number=input.nextInt();
System.out.println("sum: "+sumDigits (number));
}
public static int sumDigits(int number) {
int sum = 0;
while (number > 0) {
sum = sum + number % 10;
number = number / 10;
}
return sum;
}
}
I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;
I have an assignment to break an integer into it's individual digits, report them back to the user, and add them. I can do that, but I'm struggling with supporting negative integers. Here's my code, which works exactly the way I want it to, but only for positive integers:
import java.util.*;
public class Module4e
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i]);
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
I've found plenty of hints for getting this to work with positive integers, but none for negatives.
Use RegExp
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestDigits {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Validate Input
String number = console.nextLine();
Pattern p = Pattern.compile("(-?[0-9]{1})+");
Matcher m = p.matcher(number);
if (!m.matches()) {
throw new IllegalArgumentException("Invalid Numbers");
}
// Calculate
p = Pattern.compile("-?[0-9]{1}+");
m = p.matcher(number);
int result = 0;
System.out.print("The digits of the number are: ");
while (m.find()) {
System.out.print(m.group() + " ");
result += Integer.valueOf(m.group());
}
System.out.println("");
System.out.println("Result " + result);
}
}
// I think you can use this code //also you can multiply the number by -1
int positive = 0;
//positive give you information about the number introduced by the user
if (myNum.charAt(0)=='-'){
positive=1;
}else{
positive=0;
for (int i=positive; i<myNum.length(); i++){
//be carefull with index out of bound exception
if ((i+1)<myNum.length()){
upNum[i]=myNum.substring(i,i+1);
}
}
Change the statement String myNum=console.nextLine() to String myNum = String.valueOf(Math.abs(Integer.valueOf(console.nextLine())));
You do not have to use String to solve this problem. Here's my thought.
import java.util.*;
public class Module4e throws IllegalArgumentException {
static Scanner console=new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
if (!console.hasNextInt()) throw new IllegalArgumentException();
int myNum=console.nextInt();
myNum = Math.abs(myNum);
int sum=0;
System.out.println("\n");
System.out.print("The digits of the number are: ");
While (myNum > 10) {
System.out.print(myNum % 10);
System.out.print(" ");
sum += myNum % 10;
myNum /= 10;
}
System.out.println(myNum);
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
Try this. I gave -51 as input and got -6 as output. This is what you are looking for?
import java.util.*;
public class LoggingApp
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
int multiple = 1;
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
Integer myNumInt = Integer.parseInt(myNum);
if (myNumInt < 1){
multiple = -1;
myNum = Integer.toString(myNumInt*-1);
}
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i])*multiple;
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
I'm trying to create a method that will take a number and determine whether the number is an odd, abundant number with the sigma function. An abundant number is any number that when put into the sigma function generates a sum greater than the number given.
For instance, sigma(12) is abundant because sigma(12) = 1+2+3+4+6+12 = 28. However, it is not odd, so my method would not consider it. I can't figure out why my loop function isn't working , because when I try to input a range it spits up a bunch of number gibberish. Here's what I have so far:
import java.util.*;
public class OddAbundant {
static Scanner input = new Scanner(System.in);
public static void findOddAbundant(){
System.out.println("Please enter the start of the range you want to test for odd abundant integers");
int startRange = input.nextInt();
System.out.println("Please enter the end of the range you want to test for odd abundant integers");
int endRange = input.nextInt();
for(int b = startRange; b <= endRange; b++) {
if (Sigma.Sigma(b)<(b*2))
continue;
else{
if (b % 2 == 1)
System.out.println(b);
}
}
}
public static void main(String[] args) {
findOddAbundant();
}
}
I go through the loop and I can't figure out what's going wrong. I've tested the sigma method, which I can provide if it will help you guys, and it does spit out the correct value when given an integer. Thoughts?
Here is my sigma function:
import java.util.*;
public class Sigma {
static Scanner input = new Scanner(System.in);
public static int Sigma(int s){
int a = 0;
for(int i=1;i<=s;i++){
if(s%i==0)
a = a + i;
}
System.out.print(a);
return a;
}
public static void main(String[] args) {
System.out.println("Please enter the number you want to perform the sigma function on");
int s = input.nextInt();
Sigma.Sigma(s);
System.out.print(" is the sum of all the divisors of your input" );
}
}
The silly problem it was; remove the print statement from Sigma function.
public static int Sigma(int s){
int a = 0;
for(int i=1;i<=s;i++){
if(s%i==0)
a = a + i;
}
System.out.print(a); //why do you have it here?
return a;
}
The code works. But, I need to include long integers. How can I do that? I've tried a million things. I'm not good at this either so it takes me 5 times longer to get a simple code. Please help.
import java.util.Scanner;
public class Exercise2_6M
{
public static void main(String[] args)
{
// Create a Scanner
Scanner input = new Scanner(System.in);
// Enter amount
System.out.print("Enter an integer:");
int integer = input.nextInt();
// Calculations
int rinteger = Math. abs (integer);
int sum = 0;
int i=0;
while(rinteger / Math.pow(10,i) > 0)
{
sum+=getDigit(rinteger,i);
i++;
}
// Display results
System.out.println("Sum all digits in " + integer + " is " + sum);
}
public static int getDigit(int num, int power)
{
return (num % (int)Math.pow(10,power+1)) / (int)Math.pow(10,power);
}
}
Read the input value as a string and then use the BigInteger class to perform calculations with very large values.
A recursive solution can be much leaner:
import java.util.Scanner;
public class Exercise2_6M
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
System.out.print ("Enter an long:");
long lng = input.nextLong ();
int sum = getDigitSum (lng);
System.out.println ("Sum all digits in " + lng + " is " + sum);
}
public static int getDigitSum (long num)
{
if (num < 10L) return (int) num;
else return ((int)(num % 10)) + getDigitSum (num/10L);
}
}