I'm wrote a program to check if a number is a prime. I wanted to use the following method for checking to see if a number is prime: for number P take the factorial of p-1 then add 1 to your result. Finally divid the result by p. for dose of you that don't know, if the result is a whole number then its a prime.
anyways my code works up to prime number 167 but the gives me an NaN error for any number greater than 167.
can any body spot whats wrong?
import java.util.Scanner;
public class work {
public static void main(String arg[]) {
System.out.println("Please enter a number to check if its a prime");
Scanner in = new Scanner( System.in );
int num = in.nextInt();
double t = 1;
for (int i=1; i<num; i++){
t = i * t;
}
t = t+1;
t = t / num;
System.out.println(t%1);
if ((t%1 ==0.0) && (t!= 2)){
System.out.println("it is prime");
}
else{
System.out.println("it is not a prime");
}
}
}
Well, there a limit to the numbers that a double variable can hold. 166! is a large number. The largest double is 1.7976931348623157E308. 170! is 7.257415615307994E306.
You could use BigInteger instead.
static boolean isPrime(long n) {
BigInteger num = BigInteger.valueOf(n);
BigInteger t = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; i.compareTo(num) < 0; i = i.add(BigInteger.ONE))
t = t.multiply(i);
t = t.add(BigInteger.ONE);
return t.mod(num).equals(BigInteger.ZERO);
}
Related
Fibonacci sequence is defined as a sequence of integers starting with 1 and 1, where each subsequent value is the sum of the preceding two I.e.
f(0) = 1
f(1) = 1
f(n) = f(n-1) + f(n-2) where n>=2
My goal is to calculate the sum of the first 100 even-values Fibonacci numbers.
So far I've found this code which works perfectly to calculate the sum of even numbers to 4million , however I'm unable to find edit the code so that it stops at the sum of the 100th value, rather than reaching 4million.
public class Improvement {
public static int Fibonacci(int j) {
/**
*
* Recursive took a long time so continued with iterative
*
* Complexity is n squared.. try to improve to just n
*
*/
int tmp;
int a = 2;
int b = 1;
int total = 0;
do {
if(isEven(a)) total +=a;
tmp = a + b;
b = a;
a = tmp;
} while (a < j);
return total;
}
private static boolean isEven(int a) {
return (a & 1) == 0;
}
public static void main(String[] args) {
// Notice there is no more loop here
System.out.println(Fibonacci(4_000_000));
}
}
Just to show the console from #mr1554 code answer, the first 100 even values are shown and then the sum of all is 4850741640 as can be seen below:
Any help is appreciated, thanks!
You need to use BigInteger because long easily overflows as Fibonacci's scales quite easily. BigInteger is also tricky to check whether is an odd or even number, but you can use BigInteger::testBit returning boolean as explained in this answer.
Here is some complete code:
BigInteger fibonacciSum(int count, boolean isOdd) {
int i = 0;
BigInteger sum = BigInteger.ZERO;
BigInteger current = BigInteger.ONE;
BigInteger next = BigInteger.ONE;
BigInteger temp;
while (i < count) {
temp = current;
current = current.add(next);
next = temp;
if ((current.testBit(0) && isOdd) || ((!current.testBit(0) && !isOdd))) {
sum = sum.add(current);
i++;
}
}
return sum;
}
Or you can have some fun with Stream API:
BigInteger fibonacciSum(int count, boolean isOdd) {
final BigInteger[] firstSecond = new BigInteger[] {BigInteger.ONE, BigInteger.ONE};
return Stream.iterate(
firstSecond,
num -> new BigInteger[] { num[1], num[0].add(num[1]) })
.filter(pair ->
(pair[1].testBit(0) && isOdd) ||
(!pair[1].testBit(0) && !isOdd))
.limit(count)
.map(pair -> pair[1])
.reduce(BigInteger.ZERO, BigInteger::add);
}
In any way, don't forget to test it out:
#Test
void test() {
assertThat(
fibonacciSum(100, false),
is(new BigInteger("290905784918002003245752779317049533129517076702883498623284700")));
}
You said.
My goal is to calculate the sum of the first 100 even-values Fibonacci numbers.
That number gets very large very quickly. You need to:
use BigInteger
use the mod function to determine if even
For this I could have started from (1,1) but it's only one term so ...
BigInteger m = BigInteger.ZERO;
BigInteger n = BigInteger.ONE;
BigInteger sumOfEven= BigInteger.ZERO;
int count = 0;
BigInteger t;
while( count < 100) {
t = n.add(m);
// check if even
if (t.mod(BigInteger.TWO).equals(BigInteger.ZERO)) {
sumOfEven = sumOfEven.add(t);
count++;
}
n = m;
m = t;
}
System.out.println(sumOfEven);
Prints
290905784918002003245752779317049533129517076702883498623284700
If, on the other hand, from your comment.
My aim is to calculate the sum of the first 100 even numbers
Then you can do that like so
sumFirstNeven = (((2N + 2)N)/2 = (N+1)N
so (101)100 = 10100 and the complexity is O(1)
as I figured, you want a program to sum 100 first even values of the Fibonacci series.
here is a sample code, when you run the program it will ask you to determine the number of the even values, you want 100 value e.g, type 100 in consul:
public static void main(String[] args) {
int firstNumber = 0;
int secondNumber = 2;
System.out.print("Enter the number of odd elements of the Fibonacci Series to sum : ");
Scanner scan = new Scanner(System.in);
int elementCount = scan.nextInt(); // number of even values you want
System.out.print(firstNumber + ", ");
System.out.print(secondNumber + ", ");
long sum = 2;
for (int i = 2; i < elementCount; i++) {
int nextNumber = firstNumber + secondNumber;
System.out.print(nextNumber + ", ");
sum += (nextNumber);
firstNumber = secondNumber;
secondNumber = nextNumber;
}
System.out.print("...");
System.out.println("\n" + "the sum of " + elementCount + " values of fibonacci series is: " + sum);
}
I am trying to make a program where a user enters 2 numbers, and then the program gives the tau numbers in this gap.
"Tau" number is the number which can divided by its total number of dividers.For example (1,2,3,4,6,8,12,24) all this numbers can divide 24. There is 8 numbers then 24 can divided by 8. So we can say 24 is a tau number.*
There is a mistake at second for loop I think but I cannot understand where is it.
import java.util.Scanner;
public class tauNumber {
public static void main(String [] args){
int start=0,stop=0,count=0;
Scanner input =new Scanner(System.in);
System.out.println("Please enter first number: ");
start=input.nextInt();
System.out.println("Please enter last number: ");
stop=input.nextInt();
for(int i=0+start;i<=stop;i++){
for(int j=1;j<=start;j++){
if(i%j==0){
count++;
}
}
if(start/count==0){
System.out.println(i+" is a tau number" );
}
}
}
}
Instead of saying "tau number" you should just refer to it as a refactorable number as #Tunaki pointed out.
I would suggest that you split your code up into functions to get a better understanding on whats going on, I think this is what you're looking for:
import java.util.Scanner;
class TauNumber {
public static void main(String[] args){
Scanner input =new Scanner(System.in);
System.out.println("Please enter first number: ");
int start=input.nextInt();
System.out.println("Please enter last number: ");
int stop=input.nextInt();
for(int i=start+1; i<stop; i++){
if(refractorable(i)){
System.out.println("Found tau number: "+ i);
break;
}
}
}
public static boolean refractorable(int number){
if(sumDivisors(number) == 0) return false;
if(number % sumDivisors(number) == 0){
return true;
} else {
return false;
}
}
public static int sumDivisors(int number){
int sum = 0;
for(int i=1; i<=number; i++){
if(number % i == 0){
sum++;
}
}
return sum;
}
}
Note: I would also like to point out that when you specify "gap" what do you mean by it? I took it as start < x < stop, because that would be the gap but it could certainly be start < x <= stop.
The fault in your code is that you check whether the quotient of start/count is 0. To check whether start is divisible by count, you should check whether the remainder is 0. Therefore, you should use the modulus (%) operator instead of the division (/) operator.
Below is a function's code that checks whether its argument is a tau number.
private static boolean isTau(int tau){
int count = 0;
for(int i=1; i<=tau; i++){
if(tau % i == 0)
count++;
}
return (tau % count == 0) ; //returns true if 'tau' is a tau number
}
In the main method, you can make use of this function like this:
for(int i=start; i<=stop; i++){
if(isTau(i))
System.out.println(i+" is a tau number");
}
I need to find the smallest number which digit numbers product is equal to a given num.
import java.util.Scanner;
class timus_1014_2 {
public static void main(String[] args){
int[] arr = new int[10]; // eskan ban# chem imanum inchi a statik,
int prod = 1;
int j = 0;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 2; i < 10; ++i){
if (n % i == 0) {
arr[j] = i;
j++;
}
}
prod = prod * arr[j];
System.out.print(prod);
}
}
Something is wrong with the logic, whats is the problem when I input 10 it should give 25 but it gives 0. Please give ideas of how to make a program find a number which digits product is a given num.
If I understood your problem correctly you need a number whose product of digits equals a number N. Since you asked for new algorithm , you can chck following code.
Logic:
Note : For number whose prime factors are less than 10
Get all factors from 9 -> 2
add to list
print in reverse or use stack instead of list
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number");
int num = in.nextInt();
List<Integer> lst = new ArrayList<>();
for (int p = 9; p >= 2; p--) {
while (num % p == 0) {
num /= p;
lst.add(p);
}
}
String smallestNumber = "";
for (int i = lst.size() - 1; i >= 0; i--) {
smallestNumber = smallestNumber + lst.get(i);
}
System.out.println("Smallest number : " + smallestNumber);
}
}
Output :
Enter number
10
Smallest number : 25
Enter number
144
Smallest number : 289
Enter number
12
Smallest number : 26
I suggest you look at each error is fix it one by one. I also suggest you use an IDE which will show you the errors and you type and will help ensure you don't have an overwhelming number of errors and you can see if those error disappear based on your corrections.
BTW Often when you use an array for a short piece of code, it can often be eliminate as I suspect it can be removed in your case.
Static methods can not access non-static members of class.
In your case prod is member variable of class but not static. To fix the error , try to make prod as static.
private static int prod = 1;
I would prefer , to make it local variable if no other method is using it.
The problem here is you need to create an object of the particular class to call a particular method associated with it
import java.util.Scanner;
class DigPro {
static int[] arr = new int[10]; // eskan ban# chem imanum inchi a statik,
int prod = 1;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
DigPro obj = new DigPro();
obj.prime(in.nextInt());
}
public void prime(int n){
for (int i = 1; i < 10; ++i){
for (int j = 0; j < 9; ++j) {
if (n % i == 0) {
arr[j] = i;
}
prod = prod * arr[j];
}
}
System.out.print(prod);
}
}
Here you need to create an object say obj of DigPro class and then call prime(int n) method with that object. Also your division is startint with zero which is changed to one
In above code you are increasing j after the assigning value to arr[j].You should do the following:-
prod = prod * arr[j-1];
Here it will multiply prod with last array updated. That is why you are getting zero. And for your another question find the smallest number which digit numbers product is equal to a given num has similar answer at this link.
Since this is actually a pretty interesting problem, I took the time to come up with a correct solution for all possible integer inputs.
import java.util.*;
public class Main{
public static void main(String[] args) {
System.out.println("Enter number:");
int number = new Scanner(System.in).nextInt();
Stack<String> factors = new Stack<>();
if(number==0){
factors.push("0");
}else if(number==1){
factors.push("1");
}else{
for(int f=9;f>1;f--){
while(number%f==0){
factors.push(Integer.toString(f));
number/=f;
}
}
}
if(number<0){
factors.push("-");
}
if(number>9){
System.out.println("This is impossible.");
}else{
System.out.println("Smallest Number:");
while(!factors.empty()) System.out.print(factors.pop());
}
}
}
This code compiles fine, but when I run it, it asks for my two numbers as expected and then just sits there and doesn't do anything at all. I've searched the Internet and worked on this all day. I'm finally caving and asking for help.
Is the issue that it's not looping back up automatically? After 10 hours at this, I've found nothing.
import java.util.Scanner;
public class EA
{
public static void main (String[] args)
{
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
//do the calculations
while(J>0)
{
int Remainder;
Remainder = I % J;
while(Remainder>0)
{
I = J;
J = Remainder;
return;
}
System.out.println("GCD is" + J);
}
}
}
}
Among other things already mentioned, you are confusing while with if. You have put your algorithm logic inside a while loop that only runs if the first input is bad.
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
// You never reach here under ordinary conditions
}
SJuan mention that the return breaks the loop, which is true, but even if it's fixed there are a few other issues:
The inner while never end (infinite loop)
The result will be stored in J - not in I
System.out.println("GCD is " + I); Should be printed outside of the outer while!
The "heart" of your program should do this:
// we get here with valid values stored in I,J
int Remainder = I % J;
//do the calculations
while(Remainder>0)
{
I = J;
J = Remainder;
Remainder = I % J;
}
System.out.println("GCD is " + J);
There are more than 1 error: the return in the while, the algorithm and the brackets of the first while.
1) When you resolve the issue of zero, the brackets of the while must be closed suddenly after you re-assign the value of the variable J.
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
2) The algorithm for computing the gcd is the following:
function gcd(a, b)
while b ≠ 0
t := b
b := a mod t
a := t
return a
Here is the correct version of your code:
public static void main(final String[] args) {
// get first integer from user
final Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
// resolve the issue of zero
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
// do the calculations
while (J != 0) {
int Remainder;
Remainder = I % J;
I = J;
J = Remainder;
}
System.out.println("GCD is" + I);
}
The return in the middle of the loop will end the execution.
This one
while(Remainder>0)
{
I = J;
J = Remainder;
return; <------- THIS IS THE RETURN THAT BREAKS ALL
}
so it does not get to the System.out.println.
UPDATE: Also, you do input.nextInt() twice for J. Probably from your description, it keeps waiting for you for entering the third integer.
Well Euclid's algorithm has a drawback as both the inputs should be non zero to compute the Greatest common divisor . But if you want to find out the GCD when one of the input is a zero ('0') tweak the logic a bit . When one of the input is zero the GCD is 1, and 'a' should be greater than 'b' to compute GCD. Check the snippet below:
if (a < b) {
int temp = a;
a = b;
b = temp;
}
if (b == 0) {
System.out.println("1");
} else {
while (b != 0) {
r = a % b;
a = b;
b = r;
}
I don't have any idea how to display the largest and smallest number after the user enter -1.
Note: I also have to display the sum of all of this number and the average of this sum.
Here's my code so far:
public static void main(String[] args) {
// store
int cnt = 0;
int acumulator = 0;
int larger = 0;
int smaller = 0;
int number;
// inputs
System.out.println("enter the number all the number");
Scanner kb = new Scanner(System.in);
number = kb.nextInt();
// loop
while (number != -1) {
acumulator += number;
number = kb.nextInt();
cnt++;//
}
double average = (acumulator / cnt);
System.out.println(" The total of your number is=" + acumulator);
System.out.println(" The average of your number is=" + average);
}
Seems like schoolwork, but what you could do is making a var and checking in your while if the input number is higher or lower then the saved var.
if(input > max)
max = input;
And
if(input < min)
min = input;
I would make the following changes:
use a for loop instead of a while loop (you need intialization, condition and iteration)
use the JDK's API more - Math.min() and Math.max()
spell "accumulator" correctly
remove all variables you are not using (cnt)
Try this:
public static void main(String[] args) {
int accumulator = 0;
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int count = 0;
// inputs
System.out.println("enter a number (-1 to end)");
Scanner kb = new Scanner(System.in);
for(int number = kb.nextInt(); number != -1; number = kb.nextInt()) {
count++;
accumulator += number;
largest = number > largest ? number : largest;
smallest = number < smallest ? number : smallest;
}
double average = (accumulator / count);
System.out.println(" The total of your numbers is=" + accumulator);
System.out.println(" The average of your numbers is=" + average);
System.out.println(" The largest of your numbers is=" + largest);
System.out.println(" The smallest of your numbers is=" + smallest);
}
FYI: Math.min/max could be used instead of the ternary statements, but the above is the simplest java that will achieve the result.
Basically you need to check each all numbers with each other.Lets say we have numbers 1,2 and 3
here is the code:
public static void main(String[] args){
int one=1;
int two=2;
int three=3;
if(three>one){
if(three>two){
System.out.println("three is biggest");
}
}
if(two>one){
if(two>three){
}
}
etc etc.
I think you got idea
You need to use an "if" statement.