question about polynomial multiplication - java

i know that horners method for polynomial pultiplication is faster but here i dont know what is happening here is code
public class horner{
public static final int n=10;
public static final int x=7;
public static void main(String[] args){
//non fast version
int a[]=new int[]{1,2,3,4,5,6,7,8,9,10};
int xi=1;
int y=a[0];
for (int i=1;i<n;i++){
xi=x*xi;
y=y+a[i]*xi;
}
System.out.println(y);
//fast method
int y1=a[n-1];
for (int i=n-2;i>=0;i--){
y1=x*y+a[i];
}
System.out.println(y1);
}
}
result of this two methods are not same
result of first method is
462945547
and result of second method is
-1054348465
please help

You're using y on the second loop:
y1=x*y+a[i];
This is where writing two function would come in handy - it would be impossible to reuse the same variable.

Look at this loop:
for (int i=1;i<n;i++){
xi=x*xi;
y=y+a[i]*xi;
}
I think you should use
for (int i=0;i<n;i++){
xi=x*xi;
y=y+a[i]*xi;
}

Related

not able to get the sorted array

cannot able to identify my error, checked a-lot pls go through it it does not produce the correct output,
the code is implementation of quick sort through java.
this code produces the same output as input,
as i am new to java and algorithms I am not able to figure it out.
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
int a[]=new int[5];
Scanner s=new Scanner(System.in);
for(int i=0;i<5;i++)
a[i]=s.nextInt();
quick(a,0,4);
for(int i=0;i<5;i++)
System.out.print(a[i]+" ");
}
public static void quick(int a[],int s,int l)
{
if(s<l)
{
System.out.println("in quick");
int pi=part(a,s,l);
quick(a,s,pi-1);
quick(a,pi+1,l);
}
}
public static int part(int a[],int s,int l)
{
System.out.println("in part");
int pivot=a[l];
int pin=s;
for(int i=s;i<l;i++)
{
if(a[i]<=pivot)
{
swap(a[i],a[pin]);
pin++;
}
}
swap(a[pin],a[l]);
System.out.println(pin);
return pin;
}
public static void swap(int a,int b)
{
System.out.println("in swap");
int t;
t=a;
a=b;
b=t;
}
}
Your swap function doesn't work, that's why quick leaves your array untouched.
This addresses exactly your issue: Java: Why does this swap method not work? -- those are fundamental concepts and it more than pays to understand them.
Anyway, since you're working on an array, you could go about it like this:
/** Swap array[i] and array[j] */
public static void swap(int[] array, int i, int j)
{
int t = array[i];
array[i] = array[j];
array[j] = t;
}
Note: I haven't delved into the logic of your sorting -- you may be able to figure it out once this is fixed.
You're not actually swapping array elements when calling swap. All the method is doing is swapping the parameters.
You could either pass the array into the swap method along with the indices, or more practically, just copy your swap code into your part method
I have no idea whether you are learning QuickSort, but if you want a quick way to sort a list of numbers, I'd suggest you to use an ArrayList, which is basically declared like this:
ArrayList<Integer> yourArrayList = new ArrayList<Integer>();
Among the diamond operator (<>) insert the data type, in this case is Integer, but you could also insert Double, to obtain a decimal result.
After you declared it, you have to add your numbers:
yourArrayList.add(1)
yourArrayList.add(3);
etc...
When you are done use Collections.sort(yourArrayList);
I hope I was clear, this is the code to use it:
ArrayList<Integer> yourArrayList = new ArrayList<Integer>();
yourArrayList.add(10);
yourArrayList.add(3);
yourArrayList.add(7);
yourArrayList.add(-3);
Collections.sort(yourArrayList);
System.out.println(yourArrayList);

error: incompatible types: int[][] cannot be converted to int

As you can see in below code, I am trying to add two (2-D integer ARRAYS),I know that variable (c) in the first method is a reference to the array , why can not I return that array or it's reference , Can I return 2-D array in general ,how?
import java.util.*;
public class Matrix_Addition {
public static int sum (int[][]a,int[][]b){
int[][]c=new int [a.length][b[1].length];
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
c[i][j]=a[i][j]+b[i][j];
}
return c;
}
public static void display(int[][]a){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
System.out.println(a[i][j]);
}
}
public static void main(String[] args) {
int[][]a={{1,2,3},
{4,5,6},
{7,8,9}};
int[][]b={{9,8,7}
,{6,5,4},
{3,2,1}};
int[][]c=sum(a,b);
display(a);
display(c);
}
}
c is an array/matrix but you try to return an int, try
public static int[][] sum (int[][]a,int[][]b) {
In general you should specificy in which line java tells you the error appears when asking a question.
Hope it helps!
Since you have declared c as a 2-D array (int[][]c=new int [a.length][b[1].length])
Your sum method returns int and you are trying to return int 2-D array so it is giving you an error that incompatible types: int[][] cannot be converted to int
You should change return type to your sum method from int to int[][].
public static int[][] sum (int[][]a,int[][]b){
You can use the same type as on input:
public static int[][] sum(int[][] a, int[][] b)
Change you main function this line of code..
int[][]c=sum(a,b);
with
int c=sum(a,b);
and all the downline code like this...
display(a);
display(b);
System.out.println(c);
this will works. because if you see your add() function definition
public static int sum (int[][]a,int[][]b){.....} // return type is int not int[][].
Reason : Return type of sum(int[][], int[][]) is int not int[][].

printing method class randTest (int n)

I am having trouble printing out the method randTest (int n) as errors keep appearing. I want to print this method in the main as i want to print the results in a clear tabular form. The method must stay static void. This is my code below:
public class RandNumGenerator {
public static int RandInt(){
double n = Math.random()*10;
return (int) n;
}
public static void randTest(int n){
int [] counts = new int [10];
for(int i=0;i<n;i++){
counts[i] = RandInt();
System.out.println(counts[i]);
}
}
public static void main(String[] args) {
System.out.println(RandInt());
System.out.println(randTest());
}
}
Just call the method randTest() instead of printing it. The work of printing is already done inside the method. And randTest takes in an argument of the type int. So, you need to save the return of RandInt and then pass it into the method.
public static void main(String[] args) {
int randInt = RandInt();
System.out.println(randInt);
randTest(randInt);
}

How to call java method on main class

I'm a beginner in Java and I have a very simple problem. I'm trying to finish an activity and I forgot how to call a method on the main class.
I keep getting an error whenever I try ways to call the computeSum method on the main class.
Error: Error: Main method not found in class array.Array, please define the main method as: public static void main(String[] args)
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
}
public int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
Suppose if your class is there in com.arr package. you can specify the qualified name of the class at the time of creating object. Because Array class is already available in java.util package. It is better to create object to your Array class along with package name.
public static void main(String[] args){
com.arr.Array a1 = new com.arr.Array();
int[] numberArray = {1,7,9,0,45,2,89,47,3,-1,90,10,100};
a1.computeSum(numberArray);
}
computeSum() it's an instance method. we have to create Object to your class for calling the instance methods.
You can try this
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
int[] nums = {1,2,3,4,5};
int sum=computeSum(nums);
System.out.println(sum);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
You need to create an instance to invoke member method of a class.
public static void main(String[] args ){
Array myArray = new Array();
int[] values = new int[] {1,2,3,4};
myArray.computeSum(values);
}
You can read about instance methods and static methods.
computeSum() is an instance method, which means it would need an object of Class Array to be called, example:
public static void main(String[] args){
Array array = new Array();
int[] nums = {1,2,3};
array.computeSum(nums);
}
Alternatively, you could make it a static method to use it without making an object, which is not recommended, but incase you want, this is how you can do it:
public class Array{
public static void main(String[] args ){
int[] nums = {1,2,3};
int sum = computeSum(nums);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
First you need to understand the difference between static classes/members and instance classes/members.
Your main method is static - as is standard for the entry method of a program - meaning it is available immediately without any binding to an instance of the Array object.
Your computeSum method is an instance method. Meaning that you need an instance of the object Array, to use it, and it will execute in that object's context.
Your choices:
1)
Make computeSum static:
public static void main(String[] args) {
computeSum({1,2,3}); // or Array.computeSum() outside of Array
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
2)
Make an instance of the Array object:
public static void main(String[] args){
Array myArray = new Array();
myArray().computeSum({1,2,3});
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
Static code - not ran in the context of an object's instance - can not reference members that are not static, this makes sense as, how would it know what object instance of that member you are referencing (myArray1.computeSum()? or myArray2.computeSum()? It doesn't even know these two instances of the myArray object exist).
Hope this helps. :)
Or you could use reflection just for a change ;)
https://docs.oracle.com/javase/tutorial/reflect/
Firstly your method have an attribute which is "int[] nums " to call the method you need to set a value to your attribute .
NOTE that you don't have to give the same name to your attribute while calling.
for example : 1 - int[] Myattribute = {1,2,3};
int sum = computeSum(Myattribute );
put this line incide your Main it ill work

Fibonacci Sequence return argument

I need to generate a program that generates the Fibonacci Sequence
Here is what I have so far:
import java.util.Scanner;
public class FibonacciRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter n:");
int n = in.nextInt();
EP64 fg = new EP64();
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber());
}
}
public class EP64
{
public static void nextNumber(int n)
{
int fold1 = 1;
int fold2 = 1;
int fnew = fold1 + fold2;
fold1 = fnew;
}
}
I get an error on:
System.out.println(fg.nextNumber());
saying:
method nextNumber in class EP64 cannot be applied to given types:
required: int
found: no arguments
reason: actual and formal argument lists differ in length
and can someone also tell me if I am doing this program right? If not, help! I looked at other similar questions but I cannot make much sense of them
Thank you all!
method nextNumber in class EP64 cannot be applied to given types: required: int found: no arguments reason: actual and formal argument lists differ in length
Your
public static void nextNumber(int n)
^^^^^^^
says that any call to the method must provide an integer as argument. But here:
System.out.println(fg.nextNumber());
^^ you need to add an integer argument
you violate this by providing no argument.
As your code reads now, I'd probably drop the int n argument.
and can someone also tell me if I am doing this program right?
Naah, not really...
fold1 and fold2 should probably be member variables (so they don't get reset in every call to the method),
You're forgetting to update fold2 (you only update fold1),
Also, you probably want to return an int from the nextNumber method.
Read up on
Official Java Tutorial: Defining Methods
You are calling a static method to a object reference instead of the class itself.
And
Not passing any argument at all for nextNumber() method.
Make the method non-static as :
public void nextNumber(int n) {}
Pass arg to the method as :
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber(n));
And also don't forget to return the processed number from your nextNumber method,which you collecting in System.out.println.
Your declaration of nextNumber says it takes an int argument, but you are calling it with no arguments.
Also, your code isn't going to do what you want. You probably should make fold1 and fold2 members of class EP64 and make the method an instance method rather than a static method. You also need to do fold2 = fold1; before you update fold1.
Finally, you need to declare nextNumber to return an int value, and then actually have it return an int value.
You have two problems. Firstly, your method doesn't return anything, i.e. it is void. You need to make it int and add a return fnew; at the end. The other problem is you are starting from scratch every time, it will return 2 each time. You need to make fold1 and fold2 fields by moving them above the nextNumber line. Oh, and drop the int n argument as it doesn't do anything.
I agree on the diagnostics of the other posts, but don't suggest a member variable, but a rename and local variables.
You can ask for the 5th Fibonacci-Number with 5 calls to
fib.next ();
or with a single call to
fib (5);
Since the fibonacci-sequence increases very rapidly, you have very few calls (54) before hitting the overflow boundary. So if you repeatedly recalc the same sequence, to print the sequence, it's not a big problem. A recursive solution would be fine.
Btw.: EP64 is a very bad name.
I think this is enough:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
int a=0,b=1,c;
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
If you want to call this as a method then:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
callFibonocci(n);
}
public static void callFibonocci(int n)
{
int a=0,b=1,c;
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
You can call this method out of the class;
// Fibnocci Using c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeProject
{
class FibnocciSeries
{
public int[] FibonacciArray(int length)
{
int[] fseries = new int[length];
fseries[0] = 0;
fseries[1] = 1;
if (length == 0)
return null;
//Iterating through the loup to add adjacent numbers and create the memeber of series
for (int i = 2; i < length; i++)
{
fseries[i] = fseries[i - 1] + fseries[i - 2];
}
return fseries;
}
}
}
////////////////////
class Program
{
static void Main(string[] args)
{
FibnocciSeries fb = new FibnocciSeries();
Console.WriteLine("Please Enter Integer Length of Fibnocci series");
int length = Convert.ToInt32(Console.ReadLine());
int[] result = fb.FibonacciArray(length);
foreach(int i in result)
Console.Write(i.ToString()+ " ");
Console.ReadLine();
}
}
|

Categories