class Labo21
{
public static void main(String [] arguments){
int n;
int i;
double somme;
System.out.print("Positive number: ");
n = Clavier.lireInt(); //keyboard
if( n <= 0){
System.out.print("ERROR");
}else{
i = 2;
somme = 1;
while (n <= i){
somme = somme + 1.0 / i;
i = i + 1;
}
System.out.print("Result: " + somme);
}
}
}
I try to know why I cannot enter the while loop.
This code has a problem with its mentality. You are lucky that it is not going into the loop though. If it so, it would run without stopping and you cannot understand it.
BECAUSE: in your code you say the condition of while loop is i should be equal to or greater than n. I guess Clavier.lireInt(); getting value from user. So if user enters 1 condition will be while( 1 <= 2) then it will go through the while loop. Increment the i, then i will be 3 again greater than n, increment i then 4 will be greater than n. It will go like that.
I thing your condition should be :
while(n>=i)
Then you can enter n as 5 and count i = 2 to 5.
Am I correct ?
Your number needs to be greater than 0 based on your if condition. To get into the while loop, your number needs to be less than or equal to 2 since you set i equal to 2. So your options are 1 or 2.
With that being said, once you're inside the while loop, you will never be able to exit (you have created an infinite loop) because n will always be less than i. Your i is incrementing by 1 on each loop iteration, and n is never changing, so it will never be greater than i. You should add a terminating condition (some way to exit the loop).
Provide 1 or 2 as Clavier.lireInt() and you will go inside the loop.
Example :
class Labo21 {
public static void main(String[] arguments) {
int n;
int i;
double somme;
System.out.print("Positive number: ");
n = 1; //Clavier.lireInt(); //keyboard
if (n <= 0) {
System.out.print("ERROR");
} else {
i = 2;
somme = 1;
while (n <= i) {
System.out.println("in loop");
somme = somme + 1.0 / i;
i = i + 1;
}
System.out.print("Result: " + somme);
}
}
}
Related
A perfect number is a number that's equal to the sum of all its positive divisors, excluding itself.
For my homework, I'm trying to write a program to find all four perfect numbers under 10000, but my code doesn't work when I run it and I'm not sure why (it just runs for a second or two, and then says "build successful" after not printing anything). I included it below, along with some comments that explain my thought process. Can someone help me out and tell me what's wrong with it?
public class HomeworkTwo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Variable declaration
int n;
int possibleFactor;
int factorSum=0;
/**For each n, the program looks through all positive integers less than n
and tries to find factors of n. Once found, it adds them
together and checks if the sum equals n. Then it repeats till n=9999. **/
for (n=2; n<10000; n++) {
for (possibleFactor = 1; possibleFactor < n; possibleFactor++) {
if (n % possibleFactor == 0) {
factorSum = possibleFactor + factorSum;
}
//Is the number perfect? Printing
if (factorSum == n) {
System.out.println(""+ n +" is a perfect number.");
}
}
}
}
}
You initialize factorSum to 0 before the first for loop, but you don't reset it to 0 when trying each new n. The factors keep adding up and are never equal tot he number to check. Reset it to 0 at the beginning of the n for loop.
Also, you may want to move the test and print of the number being a perfect number after the inner for loop, but before the end of the outer for loop, or else it may print more than necessary.
You have a few problems with your program:
You need to reset factorSum to 0 after looping through the factors
You should check your factorSum == n AFTER adding all the factors, not inside the loop.
You only need to check up to n/2; for example 10 will never be divisible by 7.
Here's the resulting program (with slightly better formatting):
public class HomeworkTwo {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
// Variable declaration
int n;
int possibleFactor;
int factorSum = 0;
/**
* For each n, the program looks through all positive integers less than n
* and tries to find factors of n. Once found, it adds them together and
* checks if the sum equals n. Then it repeats till n=9999.
**/
for (n = 2; n < 10000; n++) {
factorSum = 0;
for (possibleFactor = 1; possibleFactor <= n / 2; possibleFactor++) {
if (n % possibleFactor == 0) {
factorSum = possibleFactor + factorSum;
}
}
// Is the number perfect? Printing
if (factorSum == n) {
System.out.println("" + n + " is a perfect number.");
}
}
}
}
I suppose you already did it, but anyway, the main problem in your code is the "factorSum" variable. After checking each number, you should set it to 0 again. I addition, I used printf instead println, but it is the same:
public static void main(String[] args) {
int number = 0;
int factor = 0;
int factorSum = 0;
for(number = 2; number < 10000; number++) { //for each number we will check the possible factors.
factorSum = 0;
for(factor = 1; factor < number; factor++)
if((number % factor) == 0) { //if it is a factor, we add his value to factorSum.
factorSum = factorSum + factor;
}
if(factorSum == number) {
System.out.printf("The number: %d is a perfect number.\n", number);
}
}
}
You should keep it like this
for (n=2; n<10000; n++) {
for (possibleFactor = 1; possibleFactor < n; possibleFactor++) {
if (n % possibleFactor == 0) {
factorSum = possibleFactor + factorSum;
}
}
//Is the number perfect? Printing
if (factorSum == n) {
System.out.println(""+ n +" is a perfect number.");
}
factorSum = 0;
}
I am trying to increment the counter by whatever number the user inputs. I have been at this for almost an hour now and cannot figure it out. Any ideas?
Here's what I have:
if (starting < ending) {
while (i < ending) {
++i;
System.out.println(i);
}
}
else if (starting > ending) {
while (i > ending) {
--i;
System.out.println(i);
}
}
else {
System.out.println(i);
}
No matter what increment is entered, it starts at the starting number and counts up or down by 1.
It counts up or down by 1 because of ++i and --i. The ++ and -- operators are equal to i = i + 1 and i = i - 1, or i += 1 and i -= 1 respectively.
In order to increase or decrease by the amount a user enters, use i = i + userInput and i = i - userInput, or i += userInput and i -= userInput.
For example:
int userInput = 4;
if(starting < ending) {
while(i < ending) {
i = i + userInput;
System.out.println(i);
}
// ... etc
}
In your while loop, you could put:
while (i > ending){
i -= numberUserInput;
}
This will reassign i's value with itself plus the variable that holds the number the user input (named whatever you want). For addition, you could use += instead of -=.
The code snippet below checks whether a given number is a prime number. Can someone explain to me why this works? This code was on a study guide given to us for a Java exam.
public static void main(String[] args)
{
int j = 2;
int result = 0;
int number = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = reader.nextInt();
while (j <= number / 2)
{
if (number % j == 0)
{
result = 1;
}
j++;
}
if (result == 1)
{
System.out.println("Number: " + number + " is Not Prime.");
}
else
{
System.out.println("Number: " + number + " is Prime. ");
}
}
Overall theory
The condition if (number % j == 0) asks if number is exactly divisible by j
The definition of a prime is
a number divisible by only itself and 1
so if you test all numbers between 2 and number, and none of them are exactly divisible then it is a prime, otherwise it is not.
Of course you don't actually have to go all way to the number, because number cannot be exactly divisible by anything above half number.
Specific sections
While loop
This section runs through values of increasing j, if we pretend that number = 12 then it will run through j = 2,3,4,5,6
int j = 2;
.....
while (j <= number / 2)
{
........
j++;
}
If statement
This section sets result to 1, if at any point number is exactly divisible by j. result is never reset to 0 once it has been set to 1.
......
if (number % j == 0)
{
result = 1;
}
.....
Further improvements
Of course you can improve that even more because you actually need go no higher than sqrt(number) but this snippet has decided not to do that; the reason you need go no higher is because if (for example) 40 is exactly divisible by 4 it is 4*10, you don't need to test for both 4 and 10. And of those pairs one will always be below sqrt(number).
It's also worth noting that they appear to have intended to use result as a boolean, but actually used integers 0 and 1 to represent true and false instead. This is not good practice.
I've tried to comment each line to explain the processes going on, hope it helps!
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
It works by iterating over all number between 2 and half of the number entered (since any number greater than the input/2 (but less than the input) would yield a fraction). If the number input divided by j yields a 0 remainder (if (number % j == 0)) then the number input is divisible by a number other than 1 or itself. In this case result is set to 1 and the number is not a prime number.
Java java.math.BigInteger class contains a method isProbablePrime(int certainty) to check the primality of a number.
isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime.
For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.
Miller–Rabin primality algorithm is used to check primality in this method.
import java.math.BigInteger;
public class TestPrime {
public static void main(String[] args) {
int number = 83;
boolean isPrime = testPrime(number);
System.out.println(number + " is prime : " + isPrime);
}
/**
* method to test primality
* #param number
* #return boolean
*/
private static boolean testPrime(int number) {
BigInteger bValue = BigInteger.valueOf(number);
/**
* isProbablePrime method used to check primality.
* */
boolean result = bValue.isProbablePrime(1);
return result;
}
}
Output: 83 is prime : true
For more information, see my blog.
Do try
public class PalindromePrime {
private static int g ,k ,n =0,i,m ;
static String b ="";
private static Scanner scanner = new Scanner( System.in );
public static void main(String [] args) throws IOException {
System.out.print(" Please Inter Data : ");
g = scanner.nextInt();
System.out.print(" Please Inter Data 2 : ");
m = scanner.nextInt();
count(g,m);
}
//
//********************************************************************************
private static int count(int L, int R)
for( i= L ; i<= R ;i++){
int count = 0 ;
for( n = i ; n >=1 ;n -- ){
if(i%n==0){
count = count + 1 ;
}
}
if(count == 2)
{
b = b +i + "" ;
}
}
System.out.print(" Data : ");
System.out.print(" Data : \n " +b );
return R;
}
}
I have to write a program using loops that calculates the sum of all odd numbers between a and b (inclusive), where a and b are inputs.
I made this (below) and it works fine, but I noticed one problem with it: when i enter a larger number followed by a smaller number for the inputs, it returns 0, but when i enter the smaller number first it works perfectly. Any quick fixes for this? :)
import java.util.Scanner;
public class ComputeSumAAndB
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter 2 integers: "); //prompts user for ints
int a = in.nextInt();
int b = in.nextInt();
int sum = 0;
for (int j = a; j <= b; j++)
{
if (j % 2 == 1)
sum += j;
}
System.out.println("The sum of all odd numbers (inclusive) between " + a + " and "+ b + " is " + sum);
}
}
int temp;
if(a > b) {
temp = a;
a = b;
b = temp;
}
Put this right before your for loop starts.
The if checks whether a (the first number entered) is larger than b. If it is, it swaps a and b. Now your for loop will always start with the smallest number and iterate up to the larger number (because after this if, a will always be the smaller number).
Using this method has the added side effect of making your output make sense. Your output will now always say: "between [smaller number] and [larger number]".
rolfl's answer is more elegant and works perfectly fine, but when the user enters the larger number first, your output may look kind of weird: "between [larger number] and [smaller number]", etc.
You can get the smaller and larger inputs by using the Math.min() and Math.max functions....
for (int j = Math.min(a,b); j <= Math.max(a,b); j++) {
if (j % 2 == 1) {
sum += j;
}
}
It's not working because A is larger than B in the for loop, you have it iterate while A is less than or equal to B.
You could do what nhgrif says but it's changing your data.. But he is correct.
That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.
Actually you should do the following 2 things:
1 It is just just like rolfl mentioned above. You need to put the min and max in the right place in loop.
for (int j = Math.min(a,b); j <= Math.max(a,b); j++)
{
if (j % 2 == 1) {
sum += j;
}
}
2 Use if (j % 2 == 1) it is not enough to check whether the num is odd.
e.g.
a = -5, b =0;
What will be the result?
int sum = 0;
for(int j=-5;j<0;j++)
{
if(j%2 == 1)
{
sum+=j;
}
}
The value for sum will be 0.
We need to change the condition to if(!(j%2 == 0)) Then you will get the expected result.
That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.
Can any body help to understand this java program?
It just prints prime numbers, as you enter how many you want and it works well.
class PrimeNumbers
{
public static void main(String args[])
{
int n, status = 1, num = 3;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of prime numbers you want");
n = in.nextInt();
if (n >= 1)
{
System.out.println("First "+n+" prime numbers are :-");
System.out.println(2);
}
for ( int count = 2 ; count <=n ; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
count++;
}
status = 1;
num++;
}
}
}
I don't understand this for loop condition
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
why we are taking sqrt of num...which is 3....why we assumed it as 3?
Imagine that n can be divided by a number k that is greater than sqrt(n). Then you have:
n = k * j
where j is a number which must be less than sqrt(n) (if both k and j are greater than sqrt(n) then their product would be greater than n).
So you only need to find the divisors that are less than or equals to sqrt(n) and you can find those that are greater than or equals to sqrt(n) by a simple division. In my example, once you have found j, you can find k = n / j.
The line in question is basically trying to find numbers that are factors of your given number (and eliminating them as not-primes). If you find no factors of a given number then you can say that the number is prime.
As far as finding factors goes, you only need to go up to sqrt(N) because if you go any higher you are looking at numbers you have already seen before. This is because every time you find a factor you actually find two factors. If a is a factor of N then N/a and a are both factors of N.
A number N is prime if the only integers that satisfy N = A*B are 1 and N (or N and 1).
Now to check a number N as prime we could search all A from 2 to N and B from 2 to N, to see if N=A*B. That would take O(N^2) time, and is really inefficient.
It turns out that we only need to divide N by a number and see if there is a remainder. This brings it down to O(N).
And further, we don't need to check all the way from A=2 to A=N. If A is greater than sqrt(N), then B must be less than sqrt(N). Therefore we only need to check A from 2 to sqrt(N) to see if N/A has a remainder.
If I'm right there is a theory in math, saying that nearly all prime numbers can be determined when checking numbers from 2 to square root of n instead of checking all numbers from 2 to n oder 2 to n/2.
The factor of a number can lie only from 1 to sqrt of num. So instead of checking from 1 till num for its factors, we check for all numbers from 1 to sqrt(num) so see if any of them divides num. If any divides num, it is not prime, else it is. This improves efficiency of code.
A quick but dirty solution..
import java.util.Scanner;
class testing
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n, i, j, count = 1;
System.out.print("How many Numbers ? : ");
n = input.nextInt();
for(j = 1;count<=n;j++)
{
if(j==1 || j==2)
{
System.out.println(j);
count++;
continue;
}
for(i=2;i<=j/2;i++)
{
if(j%i==0)
break;
else if(i == j/2 && j%i != 0)
{
System.out.println(j);
count++;
}
}
}
}
}
public class PrimeNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList a = new ArrayList();
for (int i = 1; i <= 100; ++i) {
if (isPrime(i))
a.add(i);
}
System.out.println("List : " + a);
}
public static boolean isPrime(int value) {
if (value <= 1)
return false;
if ((value % 2) == 0)
return (value == 2);
for (int i = 3; i <= value - 1; i++) {
if (value % i == 0) {
return false;
}
}
return true;
}
}