logical error, not giving the wanted answer - java

I don't understand what I did wrong, there's no syntax error, but it's not giving out the answer I want. The algorithm is supposed to find the integer between 1 and 10000 to have the largest number of divisors, and state how many divisors it contains.
public class pract3ex11 {
public static void main (String [] args) {
int n;
int i;
int c=0;
int max=0;
int result;
int d;
for (n=2; n<10000; n++){
d=c;
c=0;
int x=n;
result = x;
for (i=1; i<x; i++){
result= result%i;
if (result==0){
c++;
}
if (c>d){
max=n;
}
}
}
System.out.println(max+" "+c);
}

When you set the max, you should also set d. Otherwise, the two get out of sync:
if (c>d){
d = c;
max=n;
}
You also need to assign 0 to d before the loop, and remove
d=c;
at the top of loop.

Possible solution :
public static void main(String[] args) {
int count;
int maxDivisors;
int number;
maxDivisors = 1;
number = 1;
for ( count = 2; count <= 10000; count ++ ) {
int x;
int divisors = 0;
for ( x = 1; x <= count; x++ ) {
if ( count % x == 0 )
divisors++;
}
if (divisors > maxDivisors) {
maxDivisors = divisors;
number = count;
}
}
System.out.println("The maximum number of divisors are " + maxDivisors);
System.out.println("Number is : " + number);
}

Related

Method to add the even/odd numbers

I have an array with several numbers:
int[] tab = {1,2,3,4};
I have to create two methods the first is the sum() method and the second is numberOdd().
It's Ok for this step !
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
public static int sum(int[] tab, int length){
int total = 0;
for(int i=0;i<length;i++){
total += tab[i];
}
return total;
}
public static int numberOdd(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 != 0){
tab[n++] = tab[i];
}
}
return n;
}
Now, I have to add the even numbers with the numberEven() method and I get the value "0".
I don't understand why I retrieve the value => 0 ???????
Here is my code:
int[] tab = {1,2,3,4};
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
length = numberEven(tab,length);
int sum_even = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
System.out.println(" 2) - Calculate the sum of the evens numbers : => " + sum_even);
}
public static int numberEven(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 == 0){
tab[n++] = tab[i];
}
}
return n;
}
For information: I share the code here => https://repl.it/repls/CriminalAdolescentKilobyte
Thank you for your help.
You need to add tab[i] to n
Having length as a parameter to numberEven does not cause any harm but you don't need it.
Given below is the working example:
public class Main {
public static void main(String[] args) {
int[] tab = { 1, 2, 3, 4 };
System.out.println(numberEven(tab));
}
public static int numberEven(int[] tab) {
int n = 0;
for (int i = 0; i < tab.length; i++) {
if (tab[i] % 2 == 0) {
n += tab[i];
}
}
return n;
}
}
Output:
6
you have changed the array in your numberOdd() method.
try replacing tab[n++] = tab[i]; with n++;
public static int sumEven(int[] tab){
int sumEven = 0;
for(int i=0;i<tab.length;i++){
if(tab[i] % 2 == 0){
sumEven = sumEven + tab[i];
}
}
return sumEven;
}
This should work.

Write a method to work out the sum of the first n odd numbers

First of all let me say I am quite new to programming its been my second week since I started so if you see any bad practice or error in code please accept my apologies.
I want to print sum of first n odd numbers. But so far I can only do the sum of odd number up to the given number. kindly help.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int sum = 0;
for (int i = 0; i <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
}
}
return sum;
}
}
You don't have to use a loop at all
static int sumOfOdd(int num) {
return num*num;
}
For Any Arithmetic Progression, the sum of numbers is given by,
Sn=1/2×n[2a+(n-1)×d]
Where,
Sn= Sum of n numbers
n = n numbers
a = First term of an A.P
d= Common difference in an A.P
Using above formula we can derive this quick formula to calculate sum of first n odd numbers,
Sn(odd numbers)= n²
Try this it uses a for loop that increments by two to only account for odd numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
System.out.println("The sum of the first " + n + " odd numbers is: " + sumOfOddNumbers(n));
}
public static int sumOfOddNumbers(int n) {
int sum = 0;
for(int i = 1; i < n*2; i+=2) {
sum += i;
}
return sum;
}
}
Example usage:
Enter the value of n: 5
The sum of the first 5 odd numbers is: 25
Try this:
static int sumOfOdd(int num) {
int sum = 0;
for (int i = 0; i < num; i++){
sum += i*2+1;
}
return sum;
}
It sums up all odd numbers until the limit is reached.
With i*2+1 you get the next odd number. Then you add it to the sum.
Tested with System.out.println(sumOfOdd(4)); and got the expected result 16 (1+3+5+7)
Change the counter to the number of times you add an odd number to the sum value...
static int sumOfOdd(int num) {
int sum = 0;
int i = 0;
int count = 0;
do {
if(i % 2 != 0) {
sum += i;
count++;
}
i++;
} while (count < num);
return sum;
}
Or even cleaner:
static int sumOfOdd(int num) {
int sum=0;
for (int i=1;i<num*2;i+=2) {
sum=sum+i;
}
return sum;
}
You should count how many numbers have you added and in the condition to check if count of numbers you summed is less or equal than your n. Just add the counter in your for loop and set condition to: count <= num and it should work.
Every time you add a number to the sum increment the count by count++.
The code suppose to look like this:
static int sumOfOdd(int num)
{
int sum = 0;
int count = 0;
for (int i = 0, count= 0; count <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
count++;
}
}
return sum;
}
I haven't checked it, but it should be correct
Since you don't know how many loop cycles are required you have to change the exit condition of the for loop.
Or you can use a while loop exploiting the same exit condition.
static int sumOfOdd(int num){
int sum = 0;
int counter = 0;
int currentNumber = 0;
while (counter<num){
if(currentNumber % 2 != 0){
sum += currentNumber;
counter++;
}
currentNumber++;
}
return sum;
}
Here is the complete code you'd be using:
public class YourClass {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int counter = 0;
for (int i = 0;; i++)
{
int sum = 0;
if(i % 2 != 0)
{
counter++;
sum += i;
}
if(counter == num) return sum;
}
}
}
Another alternative.
static int sumOfOdd(int num) {
int sum = 0;
int last = 2*num-1;
for (int i = 1; i <= last; i+=2){
sum += i;
}
return sum;
}
Obviously return num*num; is the most efficient but if you're obliged to use a loop then this method avoids a * inside the loop.
This will be a tiny (tiny) bit more efficient than:
for (int i = 0; i < num; ++i){
sum += 2*i+1;
}
import java.util.*;
class karan{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = n;
int sumOddNumber = n * i;
System.out.println(n*i);
}
}

Sum odd numbers from a given range[a,b]?

I was practicing with some exercises from UVA Online Judge, I tried to do the Odd sum which basically is given a range[a,b], calcule the sum of all odd numbers from a to b.
I wrote the code but for some reason I don't understand I'm getting 891896832 as result when the range is [1,2] and based on the algorithm it should be 1, isn't it?
import java.util.Scanner;
public class OddSum
{
static Scanner teclado = new Scanner(System.in);
public static void main(String[] args)
{
int T = teclado.nextInt();
int[] array = new int[T];
for(int i = 0; i < array.length; i++)
{
System.out.println("Case "+(i+1)+": "+sum());
}
}
public static int sum()
{
int a=teclado.nextInt();
int b = teclado.nextInt();
int array[] = new int[1000000];
for (int i = 0; i < array.length; i++)
{
if(a%2!=0)
{
array[i]=a;
if(array[i]==(b))
{
break;
}
}
a++;
}
int res=0;
for (int i = 0; i < array.length; i++)
{
if(array[i]==1 && array[2]==0)
{
return 1;
}
else
{
res = res + array[i];
}
}
return res;
}
}
Your stopping condition is only ever checked when your interval's high end is odd.
Move
if (array[i] == (b)) {
break;
}
out of the if(a % 2 != 0) clause.
In general, I don't think you need an array, just sum the odd values in your loop instead of adding them to the array.
Keep it as simple as possible by simply keeping track of the sum along the way, as opposed to storing anything in an array. Use a for-loop and add the index to the sum if the index is an odd number:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter minimum range value: ");
int min = keyboard.nextInt();
System.out.println("Enter maximum range value: ");
int max = keyboard.nextInt();
int sum = 0;
for(int i = min; i < max; i++) {
if(i % 2 != 0) {
sum += i;
}
}
System.out.println("The sum of the odd numbers from " + min + " to " + max + " are " + sum);
}
I don't have Java installed right now, however a simple C# equivalent is as follows: (assign any values in a and b)
int a = 0;
int b = 10;
int result = 0;
for (int counter = a; counter <= b; counter++)
{
if ((counter % 2) != 0) // is odd
{
result += counter;
}
}
System.out.println("Sum: " + result);
No major dramas, simple n clean.

Program won't quit after 10 integers or 0 have been entered

Can someone help explain to me why my program won't terminate after either "0" or 10 integers have been entered? It's supposed to after, but it won't and keeps going even after either condition to quit have been met. It compiles correctly and doesn't give me any errors, so I think it has to do with my loops but I don't know what's wrong...
import java.util.Scanner;
public class Lab11
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int intArray[] = new int[10];
int size = 0;
int userInt;
do
{
do
{
System.out.print("Enter an integer in the array, or enter '0' to quit:" + " ");
userInt = scan.nextInt();
if (userInt != 0)
{
intArray[size] = userInt;
size++;
}
}
while (size <= intArray.length);
System.out.println(sum(intArray, size));
System.out.println(max(intArray, size));
System.out.println(min(intArray, size));
System.out.println(average(intArray, size));
System.out.println(stringToArray(intArray, size));
}
while (userInt !=0);
}
public static int sum(int intArray[], int size)
{
int sum = 0;
for (int a = 0; a <= size; a++)
{
sum = sum + intArray[size];
}
return sum;
}
public static int max(int intArray[], int size)
{
int max = intArray[0];
for (int b = 1; b <= size; b++)
{
if (intArray[size] > max)
{
max = intArray[size];
}
}
return max;
}
public static int min(int intArray[], int size)
{
int min = intArray[0];
for (int c = 1; c <= size; c++)
{
if (intArray[size] < min)
{
min = intArray[size];
}
}
return min;
}
public static double average(int intArray[], int size)
{
double total = 0;
double average = 0;
for (double element : intArray)
{
total = total + element;
}
if (intArray.length > 0)
{
average = total / intArray.length;
}
return average;
}
public static String stringToArray(int intArray[], int size)
{
String stringArray = "";
for (int d = 1; d <= size; d++)
{
stringArray = intArray.toString();
}
return stringArray;
}
}
The first if statement that tests for 0 is sandwiched in a do/while, and the do/while will loop your checker until your if statement is true. Place it outside your loop.
Edit: Heh the main method bit was for C, not java :)

Java method to sum any number of ints

I need to write a java method sumAll() which takes any number of integers and returns their sum.
sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20
I don't know how to do this.
If your using Java8 you can use the IntStream:
int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());
Results: 181
Just 1 line of code which will sum the array.
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
Use var args
public long sum(int... numbers){
if(numbers == null){ return 0L;}
long result = 0L;
for(int number: numbers){
result += number;
}
return result;
}
import java.util.Scanner;
public class SumAll {
public static void sumAll(int arr[]) {//initialize method return sum
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum is : " + sum);
}
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);//create scanner object
System.out.print("How many # you want to add : ");
num = input.nextInt();//return num from keyboard
int[] arr2 = new int[num];
for (int i = 0; i < arr2.length; i++) {
System.out.print("Enter Num" + (i + 1) + ": ");
arr2[i] = input.nextInt();
}
sumAll(arr2);
}
}
public static void main(String args[])
{
System.out.println(SumofAll(12,13,14,15));//Insert your number here.
{
public static int SumofAll(int...sum)//Call this method in main method.
int total=0;//Declare a variable which will hold the total value.
for(int x:sum)
{
total+=sum;
}
return total;//And return the total variable.
}
}
You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:
int sum = 0;
for (int i = 0; i < arrayLength; i++) {
sum += arrayVal[i];
}
System.out.println("the sum is" + sum);
I hope this helps.

Categories