Why doesn't my program run correctly? - java

for my school project I have to create a program that outputs perfect numbers based on how many perfect numbers the user(teacher) want. The user can pick any number from 1-4 and it should display however many number the user chooses. Here is my current code. Please ignore the sumupTo, factorial, isprime, and the testGoldbach methods, please only look at the Perfect numbers method/code.
import java.util.Scanner;
public class MyMathB
{
public static int sumUpTo(int n)
{
int sum = 0;
for (int k = 1; k <= n; k++)
sum += k;
return sum;
}
public static long factorial(int n)
{
long f = 1;
for (int k = 2; k <= n; k++)
f *= k;
return f;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
int m = 2;
while (m * m <= n)
{
if (n % m == 0)
return false;
m++;
}
return true;
}
public static void PerfectNumbers(int number)
{
System.out.println("How many perfect numbers would you like to see? Please enter an integer from 1 to 4");
Scanner s = new Scanner(System.in);
int numbersToSee = s.nextInt();
int counts = 0;
for(counts = 0; counts <= numbersToSee; counts++)
{
for (int n = 5; n <= 10000; n++)
{
int temp = 0;
for(int i = 1; i <= number / 2; i++)
{
if (number % i == 0)
{
temp += i;
}
if (temp == number)
{
System.out.println(number);
}
}
}
}
}
public static boolean testGoldbach(int bigNum)
{
for (int n = 6; n <= bigNum; n += 2)
{
boolean found2primes = false;
for (int p = 3; p <= n/2; p += 2)
{
if (isPrime(p) && isPrime(n - p))
found2primes = true;
}
if (!found2primes)
{
System.out.println(n + " is not a sum of two primes!");
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int n;
do
{
System.out.print("Enter an integer from 4 to 20: ");
n = kb.nextInt();
} while (n < 4 || n > 20);
kb.close();
System.out.println();
System.out.println("1 + ... + " + n + " = " + sumUpTo(n));
System.out.println(n + "! = " + factorial(n));
System.out.println("Primes: ");
for (int k = 1; k <= n; k++)
if (isPrime(k))
System.out.print(k + " ");
System.out.println();
System.out.println("Goldbach conjecture up to " + n + ": " + testGoldbach(n));
}
}

you didn't declare the variable "number" in your method.
Edit: you didn't SET the variable number to anything, I misworded my last statement.

Related

ADAGAME4 Spoj Wrong Answer

Below is a Archive PROBLEM from SPOJ. Sample testCase is passing, but I am getting W/A on submission. I am missing some testCase(testCases). Need help to figure out what case I am missing and/or what I am doing wrong here.
Ada the Ladybug is playing Game of Divisors against her friend Velvet Mite Vinit. The game has following rules. There is a pile of N stones between them. The player who's on move can pick at least 1 an at most σ(N) stones (where σ(N) stands for number of divisors of N). Obviously, N changes after each move. The one who won't get any stones (N == 0) loses.
As Ada the Ladybug is a lady, so she moves first. Can you decide who will be the winner? Assume that both players play optimally.
Input
The first line of input will contain 1 ≤ T ≤ 10^5, the number of test-cases.
The next T lines will contain 1 ≤ N ≤ 2*10^7, the number of stones which are initially in pile.
Output
Output the name of winner, so either "Ada" or "Vinit".
Sample Input:
8
1
3
5
6
11
1000001
1000000
29
Sample Output:
Ada
Vinit
Ada
Ada
Vinit
Vinit
Ada
Ada
CODE
import java.io.*;
public class Main
{
public static int max_size = 2 * (int)Math.pow(10,7) + 1;
//public static int max_size = 25;
//public static int max_size = 2 * (int)Math.pow(10,6) + 1;
public static boolean[] dp = new boolean[max_size];
public static int[] lastPrimeDivisor = new int[max_size];
public static int[] numOfDivisors = new int[max_size];
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
preprocess();
int t = Integer.parseInt(br.readLine());
while(t > 0)
{
int n = Integer.parseInt(br.readLine());
if(dp[n] == true)
System.out.println("Ada");
else
System.out.println("Vinit");
t--;
}
}
public static void markLastPrimeDivisor()
{
for(int i = 0 ; i < max_size ; i++)
{
lastPrimeDivisor[i] = 1;
}
for(int i = 2 ; i < max_size ; i += 2)
{
lastPrimeDivisor[i] = 2;
}
int o = (int)Math.sqrt(max_size);
for(int i = 3 ; i < max_size; i++)
{
if(lastPrimeDivisor[i] != 1)
{
continue;
}
lastPrimeDivisor[i] = i;
if(i <= o)
{
for(int j = i * i ; j < max_size ; j += 2 * i)
{
lastPrimeDivisor[j] = i;
}
}
}
/*for(int i = 1 ; i < max_size ; i++)
System.out.println("last prime of " + i + " is " + lastPrimeDivisor[i]);*/
}
public static void countDivisors(int num)
{
int original = num;
int result = 1;
int currDivisorCount = 1;
int currDivisor = lastPrimeDivisor[num];
int nextDivisor;
while(currDivisor != 1)
{
num = num / currDivisor;
nextDivisor = lastPrimeDivisor[num];
if(nextDivisor == currDivisor)
{
currDivisorCount++;
}
else
{
result = result * (currDivisorCount + 1);
currDivisorCount = 1;
currDivisor = nextDivisor;
}
}
if(num != 1)
{
result = result * (currDivisorCount + 1);
}
//System.out.println("result for num : " + original + ", " + result);
numOfDivisors[original] = result;
}
public static void countAllDivisors()
{
markLastPrimeDivisor();
for(int i = 2 ; i < max_size ; i++)
{
countDivisors(i);
//System.out.println("num of divisors of " + i + " = " + numOfDivisors[i]);
}
}
public static void preprocess()
{
countAllDivisors();
dp[0] = dp[1] = dp[2] = true;
for(int i = 3 ; i < max_size ; i++)
{
int flag = 0;
int limit = numOfDivisors[i];
//If for any i - j, we get false,for playing optimally
//the current opponent will choose to take j stones out of the
//pile as for i - j stones, the other player is not winning.
for(int j = 1 ; j <= limit; j++)
{
if(dp[i - j] == false)
{
dp[i] = true;
flag = 1;
break;
}
}
if(flag == 0)
dp[i] = false;
}
}
}
There is a subtle bug in your countDivisors() function. It assumes
that lastPrimeDivisor[num] – as the name indicates – returns the
largest prime factor of the given argument.
However, that is not the case. For example, lastPrimeDivisor[num] = 2
for all even numbers, or lastPrimeDivisor[7 * 89] = 7.
The reason is that in
public static void markLastPrimeDivisor()
{
// ...
for(int i = 3 ; i < max_size; i++)
{
// ...
if(i <= o)
{
for(int j = i * i ; j < max_size ; j += 2 * i)
{
lastPrimeDivisor[j] = i;
}
}
}
}
only array elements starting at i * i are updated.
So lastPrimeDivisor[num] is in fact some prime divisor of num, but not
necessarily the largest. As a consequence, numOfDivisors[55447] is computed
as 8 instead of the correct value 6.
Therefore in countDivisors(), the exponent of a prime factor in num
must be determined explicitly by repeated division.
Then you can use that the divisors function is multiplicative. This leads to
the following implementation:
public static void countAllDivisors() {
// Fill the `somePrimeDivisor` array:
computePrimeDivisors();
numOfDivisors[1] = 1;
for (int num = 2 ; num < max_size ; num++) {
int divisor = somePrimeDivisor[num];
if (divisor == num) {
// `num` is a prime
numOfDivisors[num] = 2;
} else {
int n = num / divisor;
int count = 1;
while (n % divisor == 0) {
count++;
n /= divisor;
}
// `divisor^count` contributes to `count + 1` in the number of divisors,
// now use multiplicative property:
numOfDivisors[num] = (count + 1) * numOfDivisors[n];
}
}
}

two subsets whose union contains all the elements and intersection contains none of the elements

A singly linked list int the same order in which they appear.Then with out changing the linked list , the program should print whether there exists a partition of the list (two subsets whose union contains all the elements and intersection contains none of the elements) whose sums,when XOR'd equals a target value. Example: -4 3 5 {{-4}{3,5},{-4,3}{5},{-4,5}{3},{-4,3,5}{0}} sums:{{-4}{8},{-1}{5},{1}{3},{4}{0}} Xor of sums:{-12,-6,2,4} assume the target is 2 and so it should print true.
enter code here
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.*;
public class Equal {
static int a;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("testing.txt"));
Scanner in = new Scanner(System.in);
sc.useDelimiter(" ");
LinkedList ll = new LinkedList();
while (sc.hasNext()) {
String s = sc.next();
/*if (s.trim().isEmpty()) {
continue;
}*/
int b=0;
ll.add(b, s);
// System.out.println(s);
b++;
}
//System.out.println("Original contents of ll: " + ll);
System.out.println(ll.size());
sc.close();
System.out.println("Enter an integer");
a = in.nextInt();
String d ;
int e=0;
int z=0;
/* int[] binary = new int[(int) Math.pow(2, N)];
for (int i = 0; i < Math.pow(2, N); i++)
{
int b = 1;
binary[i] = 0;
int num = i, count = 0;
while (num > 0)
{
if (num % 2 == 1)
count++;
binary[i] += (num % 2) * b;
num /= 2;
b = b * 10;
}
if (count == 1)
{
System.out.print("{ ");
for (int j = 0; j < N; j++)
{
if (binary[i] % 10 == 1)
System.out.print(ll+ " ");
binary[i] /= 10;
}
System.out.println("}");
}
}*/
sc.close();
int N=ll.size();
/*set_size of power set of a set with set_size
n is (2**n -1)*/
//double pow_set_size =Math.pow(2, N);
int counter, j;
/*Run from counter 000..0 to 111..1*/
for(counter = 0; counter < N; counter++)
{
for(j = 0; j < N; j++)
{
if(counter!=j)
{
//System.out.println( ll.get(counter)+"{"+ll.get(j)+"}");
}
if(counter!=j)
{
d=String.valueOf( ll.get(j));
e=Integer.parseInt(d);
System.out.println("printing subset values "+e);
if(counter==j)
{
z =z+e;
}
}
}
String b=String.valueOf( ll.get(counter));
int f=Integer.parseInt(b);
int g=e-f;
if(g==a)
{
System.out.println("true");
}
}
}
}

Luhn formula implementation in Java

I'm trying to implement a luhn formula in my java servlet application. I tried other 'valid' credit cards numbers scattering in the internet and didn't work. I just want to know if I got it correctly. Any help would be appreaciate!
public static boolean luhn(String input){
char[] creditCard = input.toCharArray();
int checkSum = 0;
boolean alternate = false;
for (int i = creditCard.length - 1; i >= 0; i --){
int m = (int)Integer.parseInt(Character.toString(creditCard[i]));
if (alternate){
m *= 2;
if (m > 9){
m = (m & 10) + 1;
}
}
checkSum += m;
alternate = true;
}
if ( (checkSum % 10) == 0){
return true;
}else{
return false;
}
}
here the working code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean repeat;
List<Integer> digits = new ArrayList<Integer>();
do {
repeat = false;
System.out.print("Enter your Credit Card Number : ");
String input = in.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c < '0' || c > '9') {
repeat = true;
digits.clear();
break;
} else {
digits.add(Integer.valueOf(c - '0'));
}
}
} while (repeat);
int[] array = new int[digits.size()];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.valueOf(digits.get(i));
}
boolean valid = check(array);
System.out.println("Valid: " + valid);
}
to check for luhn algo
public static boolean check(int[] digits) {
int sum = 0;
int length = digits.length;
for (int i = 0; i < length; i++) {
// get digits in reverse order
int digit = digits[length - i - 1];
// every 2nd number multiply with 2
if (i % 2 == 1) {
digit *= 2;
}
sum += digit > 9 ? digit - 9 : digit;
}
return sum % 10 == 0;
}
or a more refracted program might be as below
import java.util.Scanner;
public class Luhn {
private static Scanner input;
public static void main(String... args) {
input = new Scanner(System.in);
System.out.print("Enter number to validate:\n");
String pnr = input.nextLine();
boolean result = luhn(pnr);
printMessage(result);
input.close();
}
static boolean luhn(String pnr){
// this only works if you are certain all input will be at least 10 characters
int extraChars = pnr.length() - 10;
if (extraChars < 0) {
throw new IllegalArgumentException("Number length must be at least 10 characters!");
}
pnr = pnr.substring(extraChars, 10 + extraChars);
int sum = 0;
for (int i = 0; i < pnr.length(); i++){
char tmp = pnr.charAt(i);
int num = tmp - '0';
int product;
if (i % 2 != 0){
product = num * 1;
}
else{
product = num * 2;
}
if (product > 9)
product -= 9;
sum+= product;
}
return (sum % 10 == 0);
}
private static void printMessage(boolean valid) {
if (valid){
System.out.print("Valid!\r");
}
else{
System.out.print("Invalid!");
}
}
}

trying to find the sum of even fibonacci numbers to 4 million

I am trying to find the sum of the even Fibonacci numbers up untill 4 million.
I found the numbers but i can't get them add up... in the if(n % 2 ==0) loop
8
34
144
610
2584
10946
46368
196418
832040
3524578
public static void number2()
{
int number = 40;
int a, b, c;
int numLim = 0;
a = 1;
b = 2;
while(numLim < 4000000)
{
c = a + b;
a = b;
b = c;
numLim = b;
if(numLim > 4000000)
{
break;
}
int sum = 0;
if(numLim % 2 == 0)
{
System.out.println(numLim);
sum = sum + numLim;
System.out.println("sum :" +sum);
}
}
}
You must define sum outside the while loop, or it will become 0 each iteration.
int sum = 0;
...
while ...
Remember not to set sum to 0 each iteration.
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 32; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
sum += fibonacci;
System.out.println("This is the sum " +sum);
}
}
}
So I solved it like this, it's a little more efficient and the math works but Euler hates me, hope this helps.
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 31; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
if (fibonacci%2 == 0) {
sum += fibonacci;
System.out.println(sum);
}
}
}
Sorry, this code works.
Tried doing the above in Java and here is my solution that works
public static void main(String[] args) {
int first = 1;
int second = 2;
int sum = 0;
int sumOfEvenValuedTerms = second;
for (int i = 0; i < 30; i++) {
sum = first + second;
if (sum <= 4000000) {
if (sum % 2 == 0) {
sumOfEvenValuedTerms += sum;
}
first = second;
second = sum;
}
}
System.out.println(sumOfEvenValuedTerms);
}
Output is 4613732
public static int getSumOfEvenNumbers(int n) {
int prev = 0;
int i =1;
int sum = 0;
while (i<n){
int nextNumber = i + prev;
if(nextNumber %2 ==0) {
System.out.println(nextNumber);
sum +=nextNumber;
}
prev = i;
i = nextNumber;
}
return sum;
}
public class evenFib {
public static void main(String[] args) {
double a = 1, b = 2, c = 0, sum = 0;
for (double i = 0; i <= 1000; i++) {
c = a + b;
a = b;
b = c;
if (c % 2 == 0 && sum < 4000000) {
sum = sum + c;
}
}
System.out.println(sum + 2);
}
}

program to print 1-100 prime number and throw exception for composite number in given range

i have made a program to print 1-100 prime numbers.
please help me to throw exception for composite number in range of 1-100 numbers.
i am a beginner so any help will be appreciated.
public static void main(String[] args) {
System.out.println("Prime numbers from 1 - 100 are :");
int i = 0;
int x = 0;
for (i = 1; i <= 100; i++) {
int ctr = 0;
for (x = i; x >= 1; x--) {
if (i % x == 0) {
ctr = ctr + 1;
}
}
if (ctr == 2) {
System.out.println(i);
}
}
}
I'd rather implement isPrime method and call it
public static boolean isPrime(int value) {
if (value <= 1)
return false;
// There's only one even prime: that is two
if ((value % 2) == 0)
return (value == 2);
int from = (int) (Math.sqrt(value) + 1);
// You have to check possible divisors from 3 to sqrt(value)
for (int i = 3; i <= from; i += 2)
if ((value % i) == 0)
return false;
return true;
}
public static void main(String[] args) {
...
for (int i = 1; i <= 100; ++i) {
if (isPrime(i))
System.out.println(i);
else {
// i is not prime. You can do nothing, throw an exception etc
// throw new MyException("Not a prime");
}
}
}
You should add an else clause to if (ctr == 2) { and throw an exception in it. Have a look at the documentation on how to throw an exception.
put one more condition like.
else if(ctr!=2){
throw new CompositeException("composite exception occurs");}
public void primeNumber(int n1, int n2){
String primeNo= "";
System.out.print("Prime number between " + n1 +" and "+ n2 + "is/are - ");
for(int i = n1;i <=n2; i++)
{
int count = 0;
for(int j=1; j<=i; j++)
{
if(i%j==0)
{
count = count + 1;
}
}
if(count == 2) {
primeNo = primeNo + i + ", ";
}
}
System.out.print(primeNo);
}

Categories

Resources